AOA,我想回傳 . 的輸出useAuth,輸出將回傳到ProtectedRoute組件,原樣回傳到layout.js. 如果您需要更多資訊,請告訴我
私有 Route.js
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom'
import axios from 'axios';
import Cookies from 'universal-cookie';
import { useEffect } from 'react';
let ast=null;
const ProtectedRoute = ({ component: Component, ...rest }) => {
useEffect(() => {
async function useAuth () {
let as=null;
const cookies = new Cookies();
//const user = localStorage.getItem("authToken")
//const user = cookies.get("authToken");
const _id="633e9ed97968510b2689851b";
if (user) {
const config = {
headers: {
"Content-Type": "application/json",
},
};
try{
const {data}=await axios.post(
`http://localhost:5000/api/auth/Veri`,
{
_id
},
config
);
console.log("data" data.email);
if(data.email){
return (<Outlet />)
}
else{
console.log(<Outlet />);
return <Navigate to="authentication/card/login" />;
}
}
catch(error){
console.log("Error ");
ast=false;
return <Navigate to="authentication/card/login" />;
}
}
else {
ast=false;
return <Navigate to="authentication/card/login" />
}
}
useAuth() ;
}, []);
布局.js
<Route element={<PrivateRoutes/>}>
<Route element={<MainLayout />}>
{/*Dashboard*/}
<Route path="/" element={<Dashboard />} />
<Route path="dashboard/analytics" element={<Analytics />} />
<Route path="dashboard/crm" element={<Crm />} />
<Route path="dashboard/saas" element={<Saas />} />
<Route path="dashboard/e-commerce" element={<Ecommerce />} />
</Route>
</Route>
uj5u.com熱心網友回復:
您不能使用從 useEffect 回傳的組件,而應該為此使用狀態。
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom'
import axios from 'axios';
import Cookies from 'universal-cookie';
import { useEffect, useState, useNavigate } from 'react';
let ast=null;
const ProtectedRoute = ({ component: Component, ...rest }) => {
const [authenticated, setAuthenticated] = useState(null);
const navigate = useNavigate();
useEffect(() => {
let as=null;
const cookies = new Cookies();
const _id="633e9ed97968510b2689851b";
//IDK where the **user** comes from
if (user) {
const config = {
headers: {
"Content-Type": "application/json",
},
};
try{
const {data}=await axios.post(
`http://localhost:5000/api/auth/Veri`,
{
_id
},
config
);
console.log("data" ,data.email);
if(data.email){
setAuthenticated(true);
}
else{
setAuthenticated(false);
}
}
catch(error){
console.log("Error ");
ast=false;
setAuthenticated(false);
}
}
else {
ast=false;
setAuthenticated(false);
}
}
, []);
useEffect(()=>{
if(authenticated==false){
navigate("authentication/card/login");
}
}, []);
return (
authenticated ? <Outlet/> : null
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/513156.html
上一篇:輸入未更新功能反應組件中的狀態
