简体   繁体   English

当我在 react router dom v6 中使用导航时防止组件渲染

[英]Prevent Component Rendering when i use navigate in react router dom v6

hi i'm doing protected routes using react router v6 it is redirecting fine but let's say i'm in /login and i'm not authenticated and i want to go to /dashboard here /dashboard will be rendered for some few miliseconds (i can see it ) then i will be redirected to /login how can i prevent that rendering.嗨,我正在使用 react router v6 做受保护的路由,它重定向正常,但假设我在 /login 中并且我没有经过身份验证,我想 go 到 /dashboard here /dashboard 将呈现几毫秒(我可以看到它)然后我将被重定向到 /login 我如何才能阻止该渲染。 here's my code:这是我的代码:

import { useEffect, useState } from "react";
import { Route, useNavigate } from "react-router-dom";
import { Auth } from "aws-amplify";

const protectedRoute = (Comp, route = "/login") => (props) => {
  const navigate = useNavigate();
  const checkAuthState = async () => {
    try {
      await Auth.currentAuthenticatedUser();
      console.log("React Router user authenticated ");
    } catch (err) {
      console.log("React Router we have an error");
      navigate(route);
    }
  };
  useEffect(() => {
    checkAuthState();
  });
  return <Comp {...props} />;
};

export default protectedRoute;

this is how i ordered my routes in App.js这就是我在 App.js 中订购路线的方式

 <Router>
      <Routes>
        <Route path="/" element={<Navigate to="/login" replace={true} />} />
        <Route path="/login" element={<Login />} />
        <Route path="dashboard/*" element={<Dashboard />} />
        <Route path="/signup" element={<Signup />} />
        <Route path="RecoverPassword" element={<RecoverPassword />} />
        <Route path="resetPassword" element={<ResetPassword />} />
        <Route path="verifycode" element={<VerifyCode />} />
        <Route path="policy" element={<>this is policy</>} />
      </Routes>
    </Router>

You can create a flag to tell if the checking is don or not, while that you can show some loader to the user instead of the component.您可以创建一个标志来告诉是否进行检查,同时您可以向用户而不是组件显示一些加载程序。

 onst protectedRoute = (Comp, route = "/login") => (props) => { const navigate = useNavigate(); const loading = useState(false); const checkAuthState = async () => { // start checking, show loader setLoading(true) try { await Auth.currentAuthenticatedUser(); console.log("React Router user authenticated "); } catch (err) { console.log("React Router we have an error"); navigate(route); } // end checking, hide loader setLoading(false) }; useEffect(() => { checkAuthState(); }, []); if(loading) { return "loading..." } return <Comp {...props} />; };

i got it you know what was happening is that useEffect will be executed when my component mounts (i returned redirection component so it will be rendered ) what i did is putting my component into a state initialized to empty <></> then when my protected route mounts i change the state to what i want to render我明白了,你知道发生了什么事,当我的组件挂载时 useEffect 将被执行(我返回了重定向组件,因此它将被渲染)我所做的是将我的组件放入一个初始化为空 <></> 的 state 然后当我protected route mounts 我将 state 更改为我想要呈现的内容

import { useEffect, useState } from "react";
import { Route, useNavigate } from "react-router-dom";
import { Auth } from "aws-amplify";

const protectedRoute = (Comp, route = "/login") => (props) => {
  const navigate = useNavigate();
  const [corps, setCorps] = useState(<></>);

  const checkAuthState = async () => {
    try {
      await Auth.currentAuthenticatedUser();
      console.log("React Router user authenticated ");
    } catch (err) {
      console.log("React Router we have an error");
      return navigate(route);
    }
  };
  useEffect(() => {
    checkAuthState();
    setCorps(<Comp {...props} />);
  }, []);

  return corps;
};

export default protectedRoute;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM