簡體   English   中英

如何使用 React 正確重定向到登錄頁面

[英]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>
  )
}

使用connectmapStateToProps映射authentication 我認為當我注銷時我會被重定向,但我得到一個錯誤: authentication.user is null

為什么Dashboard中的if語句不重定向我? 我還嘗試將其包裝在useEffect中,並將authentication作為依賴項。

在我們的應用程序中,我們通過 history.replace 歷史文檔重定向未經身份驗證的用戶,或者您再次閱讀文檔,也許您可以在代碼反應訓練中發現錯誤

我通過編寫一個自定義鈎子來修復它:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM