首页 > 解决方案 > 如何使用 React 正确重定向到登录页面

问题描述

我有以下(redux)状态:

{
  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>
  )
}

authentication使用connect和映射mapStateToProps。我会认为,当我注销时,我会被重定向,但我得到了一个错误:authentication.user is null.

为什么if-statement inDashboard不重定向我?我还尝试将它作为依赖项包装在useEffectwith中。authentication

标签: reactjsreduxreact-routerreact-router-dom

解决方案


我通过编写一个自定义钩子来修复它:

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
  );
}

推荐阅读