【问题标题】:How to setup a private route with react hooks and redux?如何使用 react hooks 和 redux 设置私有路由?
【发布时间】:2021-05-19 09:21:52
【问题描述】:

我正在使用 React Hooks 和 Redux 设置私有路由。但是,isAuthenticated 状态的变化并未在PrivateRoute 组件中注册。然而,在我的 Redux Dev Tools 中,isAuthenticated 切换为 true。

const PrivateRoute = ({ component: Component, ...rest }) => {
  const authStatus = useSelector((state) => state.user.isAuthenticated);

  useEffect(() => {
    console.log(authStatus);
  }, [authStatus]);

  return (
    // Show the component only when the user is logged in
    // Otherwise, redirect the user to /signin page
    <Route
      {...rest}
      render={(props) =>
        authStatus ? <Component {...props} /> : <Redirect to="/join" />
      }
    />
  );
};

export default PrivateRoute;

【问题讨论】:

  • 什么时候在 redux 中填充 isAuthenticated。可能是你的价值在它还没准备好之前就被使用了
  • @ShubhamKhatri 我真的认为就是这样。如何等到值可用?
  • 在你的reducer中添加一个加载状态

标签: reactjs redux redux-toolkit


【解决方案1】:

原来我没有通过 auth 作为 prop。因此,商店中的更新未注册。请查看修复:

function AuthStatus() {
  const auth = useSelector((state) => state.user.isAuthenticated);
  return auth;
}


const PrivateRoute = ({ component: Component, auth = AuthStatus, ...rest }) => {


  return (
    // Show the component only when the user is logged in
    // Otherwise, redirect the user to /signin page
    <Route
      {...rest}
      render={(props) =>
        auth ? <Component {...props} /> : <Redirect to="/join" />
      }
    />
  );
};

export default PrivateRoute;

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2022-08-12
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多