【问题标题】:Does not Redirect to path specified in React JS不重定向到 React JS 中指定的路径
【发布时间】:2020-08-17 22:51:46
【问题描述】:
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
return <Redirect to={{
pathname: `${match.url}/${designId}`,
props: hoodieData
}} />
}
return true
})
它进入 if 语句,但不重定向到指定的路径。
【问题讨论】:
标签:
reactjs
redirect
react-redux
react-router
react-router-dom
【解决方案1】:
您想使用state 而不是props?
state: hoodieData
【解决方案2】:
<Redirect> 组件只有在渲染时返回它才能工作。您没有显示此代码所在位置的上下文,但由于它是异步的,因此不可能呈现任何内容。
你有两个选择:
1) 设置状态,导致重新渲染,然后渲染一个<Redirect>
const Example = () => {
const [redirectTo, setRedirectTo] = useState(null);
useEffect(() => {
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
setRedirectTo({
pathname: `${match.url}/${designId}`,
state: hoodieData
})
}
});
}, []);
if (redirectTo) {
return <Redirect to={redirectTo} />
}
// else, render the component as normal
}
2) 或者我会做的:使用 history.replace 代替 <Redirect> 组件
const history = useHistory();
useEffect(() => {
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
history.replace(`${match.url}/${designId}`, hoodieData);
}
});
}, []);
// render the component as normal
【解决方案3】:
您是否尝试从 api 调用返回 React JSX?这不是您应该重定向的方式。使用您的历史记录(如果您使用的是最新版本的 react 路由器,请使用历史钩子);
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
history.replace(`${match.url}/${designId}`, hoodieData);
// return <Redirect to={{
// pathname: `${match.url}/${designId}`,
// props: hoodieData
// }} />
}
return true
})
使用 useHistory 钩子 -
import { useHistory } from "react-router-dom";
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
history.replace(`${match.url}/${designId}`, hoodieData); //or history.push
// return <Redirect to={{
// pathname: `${match.url}/${designId}`,
// props: hoodieData
// }} />
}
return true
})
【解决方案4】:
成功了
AuthService.createDesigns(data).then(res => {
if (res.data.status === "success") {
const designId = res.data.data.id
history.push({
pathname: `${match.url}/${designId}`,
state: hoodieData
})
}
return true
})
感谢您的帮助。