【问题标题】:React Routes are not functioning well over LOGOUT?React Routes 在 LOGOUT 上运行不正常?
【发布时间】:2021-10-29 17:44:48
【问题描述】:

我正在开发一个需要集成身份验证功能的项目,但我遇到了重定向问题。注销后我没有登陆 /auth,它仍然驻留在 /dashboard 组件上,但如果我刷新页面,它会重定向到 /auth 组件。

测试场景:

  1. 一旦登录,然后同时注销,它会正常工作,会带你到/auth
  2. 一旦登录,输入url auth,它会同时重定向到仪表板,这绝对没问题。但在此之后,如果您尝试注销,它会注销,但网址不会重定向到auth

注销功能

const logout = () => {
    dispatch({type: actionTypes.LOGOUT})
    history.push('/auth')
    setUserProfile(null)
}

注销减速器

import { AUTH, LOGOUT, LOGIN_CODE } from '../constants/ActionTypes'
const authReducer = (state={authData: null}, action) => {
  switch (action.type) {
    case LOGOUT:
        localStorage.removeItem("userProfile")
        return {...state, authData: null}
    default:
        return state
  }
}
export default authReducer

路线

<switch>
    <Route path="/" component={()=> <Redirect to="/dashboard" />} exact />
    <PrivateRoute path="/" component={Dashboard} auth={user} exact />
    <PrivateRoute path="/dashboard" component={Dashboard} auth={user} exact />
    <PublicRoute path="/auth" component={Login} auth={user} restricted={true} exact />
<swtich>

私人路由代码

import React from 'react';
import {Route,Redirect} from 'react-router-dom';
const PrivateRoute = ({component : Component, auth, ...rest})=>{
return(
    <Route {...rest} render={props =>{
        if(!auth)
            return <Redirect to="/auth"/>
        return <Component {...props}/>
    }}/>
 )
}
export default PrivateRoute;

公共路由代码

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const PublicRoute = ({auth, component: Component, restricted, ...rest}) => {
   return (
       // restricted = false meaning public route
       // restricted = true meaning restricted route
       <Route {...rest} render={props => (
         auth && restricted ?
            <Redirect to="/" />
            : <Component {...props} />
       )} />
     );
    };
 export default PublicRoute;

【问题讨论】:

    标签: reactjs react-redux react-router react-hooks react-router-dom


    【解决方案1】:

    从'next/router'导入路由器

    然后注销后发送:

    Router.reload();

    【讨论】:

      【解决方案2】:

      注销时必须调用函数localStorage:

      localStorage.clear();
      

      它会将您重定向到您的身份验证页面。

      【讨论】:

      • 已经完成了。在注销功能中
      • 调用用户函数到useEffect useEffect(() => { logout() }, []);
      • 不,它不会那样工作。此功能将继续登录用户。
      【解决方案3】:

      我搜索了所有可能的解决方案来解决 react-router-dom 的这种不确定行为,但没有找到任何合乎逻辑的解决方案。但现在最后我想出了针对此类问题的热修复。只需在 logout 功能中添加 tiny one line sn-p。我在下面提到的最佳参考。

      logOut

      后重新加载路由
      window.location.reload()
      

      这个函数也不会保存组件和 url。一旦 logout 功能运行,将立即重定向到 auth 路由。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-03
        • 2020-09-21
        • 2018-04-29
        • 2023-01-09
        • 2018-02-20
        • 2020-01-21
        • 2021-04-26
        • 2021-01-29
        相关资源
        最近更新 更多