当没有用户登录时,PrivateRoute 不会重定向到指定的路由

时间:2021-06-13 01:42:26

标签: reactjs authentication react-router-dom

我正在使用 firebase 来处理注册登录和注销。我将“/”设置为私有路由,这样当 currentUser 登录时,它将允许用户访问该路由,但如果没有 currentUser 登录,它将重定向到“/login 路由。

但是,即使没有登录的用户或在用户单击注销导致错误后,它仍会尝试呈现“/”

这里是错误

enter image description here

这是我的 PrivateRoute.js

enter image description here

这是注销按钮处理程序

enter image description here

1 个答案:

答案 0 :(得分:0)

我使用以下示例做了类似的事情,希望它可以解决您的问题,我认为您的做法有点复杂,我更喜欢使用 history.push 进行重定向。

我发现以下内容更易于阅读并且适用于我的项目。

  const history = useHistory();
  const currentUser = useAuth();

  useEffect(() => {
    if (!currentUser) {
      history.push('/login')
    }
  }, [currentUser]);

  return (
    <Route
      {...props}
      component={props.component} />
  );