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