react - react router v6- privateRoute - 无限循环或不渲染

react - react router v6- privateRoute - infinite loop or not rendering

对这个看似重复的问题表示歉意,但它真的让我很痛苦。我正在尝试使用新的 ReactRouter v6 私有路由,我认为对我来说最好的做法是调用服务器以确保令牌有效且未被撤销。我被进入私人路线的无限循环严重殴打,典型错误

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

我的私人路线是这样的:


import React, {useCallback, useEffect, useState} from "react"
import {Outlet, Navigate} from "react-router-dom"
import {Auth} from "../../api/authApi"


const  PrivateRoute = () => {
  const [auth, setAuth] = useState(false)

  const checkAuth = useCallback(() => {
    let authApi = new Auth()
    authApi.isAuth().then(isAuthorized => (
      setAuth(isAuthorized)
    ))
  }, [])

  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  return auth ? <Outlet /> : <Navigate to="/login" />;
}

export default PrivateRoute

我的路线是:

function App() {

  return (
     <HashRouter>
       <Routes>
         <Route exact path="/login" element={<LoginPage />} />
         <Route exact path="/register" element={<RegisterPage />} />
         <Route path="/" element={
           <PrivateRoute><HomePage /></PrivateRoute>
         } />
       </Routes>
     </HashRouter>
  )
}

export default App

我将 PrivateRoute 组件更改为:

import React, {useEffect, useRef} from "react"
import {Outlet, Navigate} from "react-router-dom"
import {Auth} from "../../api/authApi"


const  PrivateRoute = () => {
  let auth = useRef(false)

  useEffect(() => {
    const checkAuth = () => {
      let authApi = new Auth()
      authApi.isAuth().then(isAuthorized => (
        auth.current = isAuthorized
      ))
    }
    checkAuth()
  }, [])

  return (auth.current ? <Outlet /> : <Navigate to="/login" />)
}

export default PrivateRoute

但仍然有同样的问题。是我遗漏了什么吗?

我试了一下,发现两个问题:

  1. 初始状态auth为false所以会第一时间导航到/login卸载PrivateRoute,然后组件PrivateRoute(unmounted)得到api 回复,我想也许这就是你收到警告的原因。 (我在最下面做了解决)
  2. RouteOutlet 组件使用错误。
         <Route path="/" element={
           <PrivateRoute><HomePage /></PrivateRoute>
         } />

应该修改为

        <Route element={<PrivateRoute />}>
          <Route path="/" element={<Home />} />
        </Route>

代码示例: