为什么组件从不返回true?



我不知道为什么我的privaterouts .js在axios调用后auth设置为true时不会返回。它总是返回

谢谢你的帮助

PrivateRoutes.js

import { Outlet, Navigate } from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
const PrivateRoutes = () => {
const [auth, setAuth] = useState(false);
const token = localStorage.getItem('token');
axios.get('http://localhost:3333/user/auth', {
headers: { authorization: "Bearer " + token }
})
.then((response) => {
setAuth(true);
})
.catch((err) => {
setAuth(false);
})

return ( auth ? <Outlet/> : <Navigate to="/"/> )

}

数据尚未加载时存在第三种状态

我建议在加载时显示一些加载动画:

import { Outlet, Navigate } from "react-router-dom";
import { useState } from "react";
import axios from "axios";
const PrivateRoutes = () => {
const [auth, setAuth] = useState(undefined);
const token = localStorage.getItem("token");
axios
.get("http://localhost:3333/user/auth", {
headers: { authorization: "Bearer " + token },
})
.then((response) => {
setAuth(true);
})
.catch((err) => {
setAuth(false);
});
if (auth === undefined) return <>loading</>;
return auth ? <Outlet /> : <Navigate to="/" />;
};

相关内容

  • 没有找到相关文章

最新更新