React登录后验证JWT有效期跳转/admin页401错误问题问询
问题根因梳理
你现有代码存在3个核心错误,共同导致了登录后无法跳转、401报错的问题:
- 私有路由组件取Context值错误,导致身份校验永远不通过
- App.js的JWT校验逻辑存在缺陷,请求触发条件、状态更新逻辑都不对
- 登录成功后立刻跳转,此时Cookie未写入、状态更新未完成,路由校验不通过被重定向回登录页
分步修复方案
1. 修复私有路由的Context取值错误
你在UidContext.Provider中传递的是包含uid和setUid的对象,私有路由直接取整个Context对象判断等于true永远返回false,修改代码:
const PrivateRoute = ({ component: Component, ...rest }) => { // 解构取uid字段,不要直接取整个Context对象 const { uid } = useContext(UidContext); return ( <Route {...rest} render={(props) => uid === true ? <Component {...props} /> : <Redirect to="/login" /> } /> ); };
2. 修复App.js的JWT校验逻辑
原逻辑中校验请求仅在uid=true时触发,且请求成功后没有更新uid状态,同时useEffect依赖错误会导致重复请求,修改后代码:
import React, { useEffect, useState } from "react"; import Routes from "./components/Routes"; import axios from "axios"; import { UidContext } from "./components/AppContext"; const App = () => { const [uid, setUid] = useState(false); const [loading, setLoading] = useState(true); const fetchToken = async () => { const config = { method: "get", url: `${process.env.REACT_APP_API_URL}jwt`, withCredentials: true, }; try { const response = await axios(config); if (response.status === 200) { // 校验成功更新uid为true setUid(true); } } catch (error) { console.log(error); setUid(false); } finally { // 无论成功失败都结束加载状态 setLoading(false); } }; // 页面初始化直接触发校验,检查用户是否已有有效Cookie useEffect(() => { fetchToken(); }, []); return ( <UidContext.Provider value={{ uid, setUid }}> <Routes Loading={loading} /> </UidContext.Provider> ); }; export default App;
3. 修复登录组件的跳转逻辑
首先确保你的登录请求配置里加了withCredentials: true,否则浏览器不会保存后端返回的Cookie;其次登录成功后加短延迟确保Cookie写入完成再跳转:
async function handleLogin(e) { e.preventDefault(); // 登录请求配置必须加withCredentials: true const config = { // 你的原有登录接口配置,比如method、url、data等 withCredentials: true, }; try { await axios(config); document.getElementById("error").innerHTML = ""; setUid(true); // 加100ms延迟确保Cookie写入、状态更新完成再跳转 setTimeout(() => { history.push("/admin"); }, 100); } catch (error) { console.log(error); document.getElementById("error").innerHTML = error; } }
内容的提问来源于stack exchange,提问作者Phaired
相关产品推荐
相关产品推荐

