我有一张互动地图,如果你点击某个国家,它会将你重定向到特定国家的页面,但重定向并不适用于我,我不明白我做错了什么。这是代码:
onClick={() => {
const {NAME} = geo.properties;
if(NAME == 'Bulgaria')
{
<Redirect to='pages/services' />
}
}}这是我的交互式地图的.js文件的完整代码:
import React, { memo } from "react";
import {
ComposableMap,
Geographies,
Geography
} from "react-simple-maps";
import { Redirect } from "react-router-dom";
import { BrowserRouter } from 'react-router-dom';
...
const MapChart = ({ setTooltipContent }) => {
return (
<>
<ComposableMap data-tip="" projectionConfig={{ scale: 200 }}>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map(geo => (
<Geography
key={geo.rsmKey}
geography={geo}
onMouseEnter={() => {
const { NAME, POP_EST } = geo.properties;
setTooltipContent(`${NAME} — ${rounded(POP_EST)}`);
}}
onMouseLeave={() => {
setTooltipContent("");
}}
onClick={() => {
const { NAME } = geo.properties;
if (NAME === 'Bulgaria') {
this.setState({ redirect: true });
}
}}
...
/>
))
}
</Geographies>
</ComposableMap>
</>
);
};
export default memo(MapChart);发布于 2020-11-02 02:56:37
问题
这不是JSX的工作方式。它不是重定向,因为函数不能返回可呈现的JSX,也不尝试导航。呈现的所有内容都需要在render函数中,或者函数组件返回中。这个处理程序什么都不回。
解决方案
您可以声明性地呈现Redirect组件,也可以强制发出导航操作。
在条件下使用Redirect组件。
// later in render/return
if (redirect) {
return <Redirect to='/pages/services' />;
}
return (
...
onClick={() => {
const { NAME } = geo.properties;
if (NAME === 'Bulgaria') {
setRedirect(true);
}
}}
...
);MapChart
const MapChart = ({ setTooltipContent }) => {
const [redirect, setRedirect] = useState(false); // <-- add redirect state
return redirect ? ( // <-- conditional render redirect
<Redirect to="/pages/services" />
) : (
<ComposableMap data-tip="" projectionConfig={{ scale: 200 }}>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map((geo) => (
<Geography
...
onClick={() => {
const { NAME } = geo.properties;
if (NAME === "Bulgaria") {
setRedirect(true); // <-- set redirect state
}
}}
...
/>
))
}
</Geographies>
</ComposableMap>
);
};使用history.replace。
onClick={() => {
const { NAME } = geo.properties;
if (NAME === 'Bulgaria') {
history.replace('/pages/services');
}
}};MapChart
const MapChart = ({ history, setTooltipContent }) => { // <-- destructure history route prop
return (
<ComposableMap data-tip="" projectionConfig={{ scale: 200 }}>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map((geo) => (
<Geography
...
onClick={() => {
const { NAME } = geo.properties;
if (NAME === "Bulgaria") {
history.replace("/pages/services"); // <-- imperative navigation
}
}}
...
/>
))
}
</Geographies>
</ComposableMap>
);
};注释:,如果MapChart不是由Route组件直接呈现的(也就是说,它没有接收https://reactrouter.com/web/api/Route/route-props),那么您可以使用https://reactrouter.com/web/api/Hooks/usehistory react钩子。
const history = useHistory();导航将与单击处理程序完全相同。
https://stackoverflow.com/questions/64638822
复制相似问题