簡體   English   中英

使用 react-router-dom v6 配置私有路由

[英]Configuring private routes with react-router-dom v6

當訪問者去/ (家)時,如果他沒有連接,我希望他被重定向到/connexion" 。我為此創建了私有路由,效果很好。現在,我想實現將重定向用戶的邏輯根據他是否連接。

我在App.jsx中有這些路線:

import ProtectedRoutes from './middlewares/ProtectedRoutes';

return (
    <>
      <Routes>
        <Route path="/connexion" element={<Login />} />
        <Route path="/auto-connexion" element={<AutoConnect />} />

        <Route element={<AppLayout />} >
          <Route element={<ProtectedRoutes />}>
            <Route path="/" element={<Home />} />
            <Route path="/logical-entity-selection" element={<LogicalEntitySelection />} />
            <Route path="/produits" element={<Products />} />
            <Route path="/produits/:id" element={<Product />} />
            <Route path="/actualites" element={<Articles />} />
            <Route path="/actualites/id" element={<Article />} />
            <Route path="/mes-parametres" element={<MyAccount />} />
            <Route path="/mes-outils-et-services" element={<MyToolsAndServices />} />
            <Route path='*' element={<Login />} />
          </Route>
        </Route>
      </Routes>
    </>
  );

這個ProtectedRoutes.tsx

import { useEffect, useState } from "react"
import { Navigate, Outlet } from "react-router-dom"
import jwt_decode from "jwt-decode"
import instance from "../api/axios"

export default function ProtectedRoutes() {
    const [isLoggedIn, setIsLoggedIn] = useState(Boolean)

    const token = window.localStorage.getItem("token") || ''
    const decodedToken: any = jwt_decode(token)
    const uuid = decodedToken.uuid

    const isAuth = async () => {
        await instance.get(`/users/${uuid}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        }).then((res) => {
            console.log(res)
            if (res.status === 200) setIsLoggedIn(true)
            return setIsLoggedIn(false)
        })
    }

    useEffect(() => {
        isAuth()
    }, [isLoggedIn])

    return isLoggedIn ? <Outlet /> : <Navigate to={'/connexion'} />
}

問題是,使用這段代碼,React 會渲染Login組件,因為它總是返回false ,即使我在請求后有狀態200並將新狀態設置為true

如何首先提出我的請求,然后為isLoggedIn設置新狀態,然后決定呈現Login組件或Home組件?

我希望我說清楚了。 如果沒有,請不要猶豫,問我。 對此有什么幫助嗎?

除了讓它正常工作之外,你還需要一個加載狀態,我稱之為isChecking 此外,您應該更改以下代碼塊,因為您將isLoggedIn設置為true ,然后設置為false

 if (res.status === 200) setIsLoggedIn(true)
 return setIsLoggedIn(false)

解決方案:

import { useEffect, useState } from "react"
import { Navigate, Outlet } from "react-router-dom"
import jwt_decode from "jwt-decode"
import instance from "../api/axios"

export default function ProtectedRoutes() {
    const [isLoggedIn, setIsLoggedIn] = useState(false)
    const [isChecking, setIsChecking] = useState(true)
    const token = window.localStorage.getItem("token") || ''
    const decodedToken: any = jwt_decode(token)
    const uuid = decodedToken.uuid

    const isAuth = async () => {
        await instance.get(`/users/${uuid}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        }).then((res) => {
            console.log(res)
            if (res.status === 200) setIsLoggedIn(true)
            setIsChecking(false);
            return;
        })
    }

    useEffect(() => {
        isAuth()
    }, [isLoggedIn])

    if(isChecking) return <p>Checking....</p>

    return isLoggedIn ? <Outlet /> : <Navigate to={'/connexion'} />
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM