React中JWT实现与多Axios请求数据刷新丢失问题咨询
解决React刷新后丢失授权状态与二次请求数据的问题
看起来你遇到的核心问题是浏览器刷新后,Redux状态没有保留二次接口的数据,且授权状态未正确恢复——这是因为你只在登录成功时触发了第二个接口请求,但刷新页面时,虽然从localStorage恢复了token和用户信息,却没有重新执行授权检查和二次数据请求的逻辑。下面是具体的修复步骤:
1. 抽离二次数据请求为独立Action
首先把获取第二类数据的逻辑从loginUser里抽出来,做成一个可复用的action,这样不管是登录后还是刷新后,都能调用它:
// 新增获取用户数据的action export const fetchUserData = userEmail => dispatch => { axios.get('2nd api', { params: { user: userEmail } }) .then(res => { // 假设你有一个action来存储这些数据,比如setUserData dispatch(setUserData(res.data)); console.log('用户数据已更新:', res.data); }) .catch(err => { console.error('获取用户数据失败:', err); }); };
2. 修改登录逻辑,复用新Action
更新loginUser,在确认用户授权后调用这个新的action,同时把授权状态存入Redux和localStorage:
export const loginUser = userData => dispatch => { axios.get('/api/users/login', { params: { userdata: userData } }) .then(res => { const { token, authorized } = res.data; // 保存token和授权状态到localStorage localStorage.setItem('jwtToken', token); localStorage.setItem('userAuthorized', authorized); // 设置请求头 setAuthToken(token); // 解码token const decoded = jwt_decode(token); // 设置当前用户,同时带上授权状态 dispatch(setCurrentUser({ ...decoded, authorized })); // 如果授权,调用抽离的action获取数据 if (authorized === "authorized") { dispatch(fetchUserData(userData.email)); } }) .catch(err => { console.error('登录失败:', err); }); };
3. 完善页面刷新时的初始化逻辑
现在修改你检查localStorage的那段代码,不仅要设置当前用户,还要根据保存的授权状态触发二次数据请求:
// 检查localStorage中的token if (localStorage.jwtToken) { setAuthToken(localStorage.jwtToken); const decoded = jwt_decode(localStorage.jwtToken); // 从localStorage读取授权状态 const authorized = localStorage.getItem('userAuthorized'); // 设置当前用户,同时带上授权状态 dispatch(setCurrentUser({ ...decoded, authorized })); // 如果用户已授权,调用fetchUserData获取数据 if (authorized === "authorized") { // 从解码后的token里取用户邮箱 dispatch(fetchUserData(decoded.email)); } }
4. 确保Reducer正确处理数据存储
最后要保证你的reducer里有对应处理setUserData的逻辑,把二次请求的数据存到state中:
// 示例reducer const initialState = { currentUser: null, userData: null, // 新增这个字段存储二次接口的数据 isAuthenticated: false }; export default function authReducer(state = initialState, action) { switch(action.type) { case SET_CURRENT_USER: return { ...state, currentUser: action.payload, isAuthenticated: !!action.payload }; case SET_USER_DATA: // 对应setUserData的action type return { ...state, userData: action.payload }; default: return state; } }
这样修改后,每次页面刷新时:
- 代码会从localStorage读取token和授权状态
- 恢复Redux中的用户登录状态和授权标识
- 如果用户已授权,自动调用第二个接口获取数据并更新到Redux state
- 组件就能从Redux中拿到二次数据,不会出现刷新后丢失的情况
内容的提问来源于stack exchange,提问作者user6687933
相关产品推荐
相关产品推荐

