React Context存储API响应时packs为undefined及Redirect跳转失效问题
问题1:packs赋值为undefined的修复
原因
axios.get()的then回调写法错误:你将dispatch作为then的第二个参数(错误回调)执行,此时dispatch读取的res是登录接口的返回值,不含packs字段。- 获取packs的接口未携带JWT鉴权头,无法拿到正确的返回数据。
修复代码(handleSubmit部分)
const handleSubmit = (e) => { e.preventDefault(); const data = { email, password }; axios .post("https://playtoshi.totafantasy.com/api/auth/login", data) .then((res) => { const token = res.data.token; localStorage.setItem("token", token); // 给packs接口添加鉴权头 return axios.get("https://playtoshi.totafantasy.com/api/packs", { headers: { Authorization: `Bearer ${token}` } }); }) .then((packRes) => { // 从packs接口的返回值取数据 dispatch({ type: "GET_DATA", packs: packRes.data.packs, loggedIn: true, }); }) .catch((err) => console.log(err)); };
问题2:Redirect跳转不生效的修复
原因
<Redirect> 只有作为组件的返回值被渲染时才会触发跳转,写在事件处理函数里的返回值不会被React识别生效。同时事件函数里读取的loggedIn是当前渲染周期的旧值,判断逻辑不会生效。
修复代码(Login组件return部分)
在组件原有return之前添加跳转判断即可:
// 登录状态为true直接渲染跳转组件 if (loggedIn) { // 如果你使用的是react-router-dom v6,Redirect已废弃,替换为 <Navigate to="/" replace /> return <Redirect to="/" />; } return ( // 你原有登录表单的JSX代码保持不变 )
内容的提问来源于stack exchange,提问作者buzz
相关产品推荐
相关产品推荐

