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语句内部,但不会重定向到指定的路径。
您想使用state
而不是props
吗?
state: hoodieData
<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
您是否试图从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
})
此有效
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
})
谢谢你的帮助。