未验证用户时重定向到登录页面

时间:2020-04-07 11:18:37

标签: reactjs authentication react-router-dom

我想在用户未通过身份验证时重定向到登录页面。 我可以检查这是componentDidMount,但它没有良好的用户体验。 我该如何使用React Router dom做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用Redirect和privateRoute。
PriveRoute组件:

function PrivateRoute({ component: Component, ...props }) {
  const isAuthenticated = true or false;
  return (
    <Route
      render={props =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
      {...props}
    />
  );
}

export default PrivateRoute;

并在您的BrowserRouter中使用它:

<PrivateRoute
    exact
    path='/home'
    component={<Home />}
/>

您可以使用redux或任何您喜欢的方法在PrivateRoute中检查已通过身份验证。