受保护路由的无限循环

18 浏览
0 Comments

受保护路由的无限循环

我正在学习如何在React中保护路由。基本上我遵循了这篇文章https://bikashxsharma.medium.com/how-to-create-private-or-protected-route-in-react-router-v6-dd6ea6f65aea,但我决定稍微改变一下,使用存储在浏览器中的cookie来获取用户信息,而不是使用localStorage。

这导致了一个无限循环,我还在苦苦思索。

有什么建议吗?

ProtectedRoutes组件如下:

import React, { useEffect, useState } from 'react';
import { Navigate, Outlet } from 'react-router';
import { userApi } from '../../api';
import { ROUTES } from '../../constants';
const ProtectedRoutes = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  useEffect(() => {
    async function getUserInfo() {
      const userInfo = await userApi.getUserInfo();
      if (userInfo) {
        setIsLoggedIn(true);
      }
    }
    getUserInfo();
  }, []);
  return isLoggedIn ?  : ;
};
export default ProtectedRoutes;

路由使用如下:

import { ROUTES } from '../constants';
const App = () => {
  return (
    
      
        }>
          }>
            } />
          
          } />
        
        }>
          } />
          } />
        
      
    
  );
};

0
0 Comments

问题:无限循环的受保护路由(Infinite loop for a protected route)

原因:在受保护的路由中发生了无限循环的问题。

解决方法:

1. 使用`react-router-dom`包替代`react-router`。

2. 添加一个`isLoading`状态,当它为`true`时显示一些加载组件(如``),或者返回`null`。

代码示例:

useEffect(() => {
  setIsLoading(true);
  async function getUserInfo() {
    const userInfo = await userApi.getUserInfo();
    setIsLoading(false);
    if (userInfo) {
      setIsLoggedIn(true);
    }
  }
  getUserInfo();
}, []);

参考链接:[react-router vs react-router-dom, when to use one or the other?](https://stackoverflow.com/questions/42684809)

0