【问题标题】:Authenticate user before redirect react application在重定向反应应用程序之前验证用户
【发布时间】:2022-11-17 13:03:22
【问题描述】:

我正在尝试构建一个受保护的路由,以便当未经身份验证的用户尝试访问某些组件时,他们将被重定向到登录页面。问题是,当用户登录并且我刷新页面时,“if”语句在我的 useEffect 触发并更新 redux 状态之前运行,因此它总是在页面刷新时将登录用户重定向回登录页面,当它应该只对用户进行身份验证并留在该页面上。我似乎无法找到解决方法。任何帮助,将不胜感激

export const ProtectedRoute = ({children}) => {
    const user = useSelector((state) => state.user)
    const [loaded, setLoaded] = useState(false);
    const navigate = useNavigate();
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(restoreUser()).then(() => setLoaded(true))
    }, []);

    if(loaded){
        if(user.user?.error){
        return navigate('/login');
        }
    }
    return children;
}

【问题讨论】:

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


    【解决方案1】:

    添加一个 useEffect 来检查用户更改

    useEffect(() => {
     if(loaded){
        if(user.user?.error){
            return navigate('/login');
            }
        }
    
    }, [user])
    

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2021-12-13
      • 2021-09-07
      • 2020-01-30
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多