处理受保护的路由逻辑

时间:2021-04-26 14:16:40

标签: reactjs redux

我正在为我的 react 项目创建一个受保护的路由,但上下文值和 redux reducers 数据不是持久的。那么,如果用户已登录,设置的最佳方式是什么,例如 isVerifiedtrue。如果 isVerified === true go to homepage else redirect to login, isVerified 需要在每次路由或刷新更改时进行变异,因为上下文或 redux 数据不是持久的。

我是否需要创建一个单独的后端 api 来检查来自客户端的令牌?然后我将在主 App.tsx 中添加一个 useEffect,例如:

useEffect(() => {
    /*make api call, and pass the token stored in the localStorage. If 
    verified success then: */
    setIsVerified(true)
}, [])

然后我可以使用 isVerified 到我的受保护路线

1 个答案:

答案 0 :(得分:0)

您可以创建一个包含受保护和非受保护组件路由的中间件组件。在每个内部只检查用户是否已登录,然后有条件地呈现。

这通常是我实施的方式,

受保护:

// AuthRoute.js
import React, { useEffect, useState } from "react";
import { Redirect, Route } from "react-router-dom";


export const AuthRoute = ({ exact = false, path, component }) => {
  const [isVerified, setIsVerified] = useState(false);

  const checkLoginSession = () => {
  // Write your verifying logic here
    const loggedUser = window.localStorage.getItem("accessToken") || "";
    return loggedUser !== "" ? true : false;
  };


  useEffect(() => {
    (async function () {
      const sessionState = await checkLoginSession();
      return setIsVerified(sessionState);
    })();
  }, []);

  return isVerified ? (
    <Route exact={exact} path={path} component={component} />
  ) : (
    <Redirect to={"/login"} />
  );
};

不受保护:

import React from "react";

import { Redirect, Route } from "react-router-dom";
import { useEffect, useState } from "react";

export const NAuthRoute = ({ exact = false, path, component }) => {
  const [isVerified, setIsVerified] = useState(false);

  const checkLoginSession = () => {
 // Write your verifying logic here
    const loggedUser = window.localStorage.getItem("accessToken") || "";
    return loggedUser !== "" ? true : false;
  };

  useEffect(() => {
    (async function () {
      const sessionState = await checkLoginSession();
      return setIsVerified(sessionState);
    })();
  }, []);

  return isVerified ? 
     <Redirect to={"/"} /> 
     : <Route exact={exact} path={path} component={component} />;
};