簡體   English   中英

React - 如何在鈎子 useEffect 內使用重定向?

[英]React - how to use redirect inside hook useEffect?

我正在嘗試將未登錄到我的應用程序的用戶重定向到登錄頁面,並且我的路由文件中的 useEffect 中有一些條件,但是當我輸入其中之一時,重定向不起作用並且我想知道它是否與 react-router-dom 有關

Route.js 文件代碼如下:

import React, { useEffect } from 'react'; // nao estava
import { PropTypes } from 'prop-types';
import { Route, Redirect, useHistory } from 'react-router-dom';

import AuthLayout from '../pages/_layouts/auth';
import DefaultLayout from '../pages/_layouts/default';

import { store } from '../store';

export default function RouteWrapper({
  component: Component,
  isPrivate,
  ...rest
}) {
  const { signed } = store.getState().auth;
  const { googleSigned } = store.getState().googleAuth;

  const history = useHistory();

  useEffect(() => {
    if (!signed && !googleSigned && isPrivate) {
      return <Redirect to="/" />;
    }

    if ((signed && !isPrivate) || (googleSigned && !isPrivate)) {

      return <Redirect to="/dashboard" />;

    }

    return <Redirect to="#" />;
  }, [googleSigned, signed]);

  const Layout =
    signed || googleSigned || window.location.pathname === '/dashboard'
      ? DefaultLayout
      : AuthLayout;

  return (
    <Route
      {...rest}
      render={(props) => (
        <Layout>
          <Component {...props} />
        </Layout>
      )}
    />
  );
}

RouteWrapper.propTypes = {
  isPrivate: PropTypes.bool,
  component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
    .isRequired,
};

RouteWrapper.defaultProps = {
  isPrivate: false,
};

signed 和 googleSigned 是 reducer 中存在的狀態,焦點是 google 簽名,因為使用正常登錄獲得的簽名尚未實現,而 google 簽名是在應用程序后端使用 oAuth 實現的

此時我的應用程序的流程如下,用戶單擊 google 上的登錄按鈕被重定向到 google 身份驗證屏幕,如果用戶在應用程序中注冊,他將被重定向到儀表板頁面、儀表板頁面並發送操作檢查用戶是否登錄到應用程序,目的是如果用戶未登錄(googleSigned = false),他將被重定向回登錄頁面

您的實施存在一些問題。 首先, useEffect返回useEffect並不像您希望它們那樣工作。 useEffect中的返回useEffect實際上用於清除副作用,例如滾動偵聽器或您不想在組件卸載后保留的類似內容。 您可以在此處閱讀更多相關信息: https : //reactjs.org/docs/hooks-effect.html

您想要做的是以編程方式重定向用戶,而不是返回重定向組件。 使用react-router-dom您可以使用useHistory鈎子 ( https://reactrouter.com/web/api/Hooks/usehistory ) 做到這一點。 因此,我們可以使用歷史代替返回useEffect鈎子中的<Redirect />組件。

useEffect(() => {
    if (!signed && !googleSigned && isPrivate) {
      history.push("/");
    }

    if ((signed && !isPrivate) || (googleSigned && !isPrivate)) {
      history.push("/dashboard");
    }

    history.push("#");

}, [googleSigned, signed]);

像上面這樣的東西應該更接近你想要實現的目標。

也許您想實現受保護的路由模式?

保護路線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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