反应 - 反应路由器 v6- privateRoute - 无限循环或不渲染

发布于 2025-01-11 09:15:34 字数 2033 浏览 0 评论 0原文

对于这个看似重复的问题表示歉意,但它确实让我很痛苦。我正在尝试使用新的 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

但仍然有相同的问题。是我缺少什么吗?

Apologies for this seemingly repated question but it is really biting me. I am trying to use the new ReactRouter v6 private routes and I think the best practice for me would be to make a call to the server to make sure the token is valid and has not been revoked. I am being badly beatean by an infinite loop entering the private route with the typical error

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.

my private route looks like this:


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

and my routes are:

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

I changed the PrivateRoute component to this:

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

but still have the same issue. Is it something I am missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雅心素梦 2025-01-18 09:15:34

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

  1. 初始状态auth为false,所以它会第一次导航到/login并卸载PrivateRoute,然后组件 PrivateRoute(已卸载)获得 api 响应,我想也许这就是您收到警告的原因。 (我在底部做了一个解决方案)
  2. RouteOutlet 组件的使用方式是错误的。
         <Route path="/" element={
           <PrivateRoute><HomePage /></PrivateRoute>
         } />

应修改为

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

代码示例:

编辑文本字段选择开始

I tried it and found two issues:

  1. The initial state auth is false so it will navigate to /login and unmount PrivateRoute at the first time, and then the component PrivateRoute(unmounted) got api response, I think maybe that's why you got warning. (I made an solution at the bottom)
  2. The Route and Outlet components are used in the wrong way.
         <Route path="/" element={
           <PrivateRoute><HomePage /></PrivateRoute>
         } />

should be modified to

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

The Code Sample :

Edit TextField selectionStart

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文