当访客进入/
(家)时,如果他没有连接,我希望他被重定向到/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>
</>
);
A this 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
组件?
我希望我说清楚了.如果没有,请毫不犹豫地问我.有什么帮助吗?