【发布时间】:2021-10-30 05:20:01
【问题描述】:
我想在页面之间切换。
我正在推动路径和 {state} 对象。
问题是当按下浏览器后退按钮时,即使我只切换两次或更多,它也会在注册和登录之间来回无休止。
或者当按下浏览器后退按钮时,URL 会更改为登录或注册,但该页面将是我的 404 组件,或者是 Main 页面(在沙箱中),无论之前的页面是什么。
两个组件在一个条件渲染中
{auth ? (
<Switch>
<Route path="/signup" auth={auth}>
<SignUp setAuth={setAuth} />
</Route>
<Route path="/signin" auth={auth}>
<SignIn setAuth={setAuth} />
</Route>
</Switch>
) :
在按钮中从注册切换到登录时 -
history.push({
pathname: "/signin",
state: { from: "fromSignUp" }
});
按下每个组件上的浏览器后退按钮将检查历史记录是否来自注册或登录 -
useEffect(() => {
window.onpopstate = () => {
console.log("useEffect SignUp", location.state?.from === "fromSignIn"); // sometimes true/sometimes false, even when came from 'signin'
if (location.state?.from === "fromSignIn") {
history.push({
pathname: "/signin",
state: { from: "fromSignUp" }
});
} else {
setAuth(false);
history.goBack();
}
};
}, [location.state, history]);
在我的 VS Code 中,它的表现更糟。
我可以提供 GitHub 存储库的链接。
谢谢
【问题讨论】:
标签: reactjs routes react-router react-router-dom history.js