[英]How to correctly redirect to the login page with React
我有以下(redux)state:
{
authentication: user
}
注銷時, user
設置為null
。
我有以下組件:
const Dashboard = ({ authentication }) => {
if (!authentication.user) {
return <Redirect to={"/login"} />
}
return (
<SomeInnerComponent />
);
}
const SomeInnerComponent = ({ authentication }) => {
const name = authentication.user.name;
return (
<h1>Hello, {name}</h1>
)
}
使用connect
和mapStateToProps
映射authentication
。 我認為當我注銷時我會被重定向,但我得到一個錯誤: authentication.user is null
。
為什么Dashboard
中的if
語句不重定向我? 我還嘗試將其包裝在useEffect
中,並將authentication
作為依賴項。
我通過編寫一個自定義鈎子來修復它:
export function useAuthentication() {
const history = useHistory();
const user = useSelector(state => state.authentication.user);
const dispatch = useDispatch();
useEffect(() => {
if (!user) {
history.push(LOGIN);
});
return { user };
}
然后可以在我的 React 組件中調用它,如下所示:
const Dashboard = () => {
const { user } = useAuthentication();
return (
// My code
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.