如何解决React 路由器在刷新时重定向到 root '/'如何更改我的逻辑,使其不这样做?
所以我有“/”、“/login”和“/today”页面。这些是路线。
App.js
<Route path="/login" exact component={Login} />
{/* Default root route */}
<Route path="/" exact render={() => <GetStarted user={user} />} />
{/* Today route */}
<Route
path="/today"
render={() =>
<Tasks headers={headers} item={task} setItem={setTask} incompleteItems={incompleteTasks}
setIncompleteItems={setIncompleteTasks} completeItems={completeTasks} setCompleteItems={setCompleteTasks}
/>}
/>
现在的问题是当我在“/today”路线上并且我刷新时,它重定向到“/”。我知道它为什么会这样做,但我不知道如何解决它。这样做是因为在登录路由上,我有一个 useEffect 来检查用户是否登录(使用 isAuthenticated
是 redux,基本上检查我状态中的令牌是否存在),如果是,我做history.push('/')
。但同样在 Today.js
中,它会检查您是否已通过身份验证,如果没有,则执行 history.push('/login')
。
因此,当我刷新今天页面时,它会转到登录路由一秒钟,然后它意识到我已通过身份验证,因此它将我推送到“/”而不是“/today”。因为我一开始猜 isAuthenticated
是假的,然后它意识到它是真的,然后转到 '/'。
我可以在 Login.js
中以任何方式执行此操作,以便它推送到我之前所在的任何链接而不是硬编码“/”?
Login.js
function Login({history,isAuthenticated,error,login}) {
// Making sure the user is redirected to root if theyre authenticated
useEffect(() => {
if (isAuthenticated) {
history.push("/")
}
},[isAuthenticated])
Today.js
function Tasks({history,headers,item,setItem,incompleteItems,setIncompleteItems,completeItems,setCompleteItems}) {
// Making sure that if the user isnt authenticated,theyre redirected to login
useEffect(() => {
if (!isAuthenticated) {
history.push("/login")
}
},[isAuthenticated])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。