如何在Next.js中使用Redux?页面跳转时Redux状态丢失如何解决
问题原因&修复方案
1. 未处理next-redux-wrapper的HYDRATE内置动作
next-redux-wrapper在同步服务端与客户端状态时会自动触发HYDRATE动作,你当前的reducer没有对该动作做处理,会导致状态被重置为初始值,所以每次页面切换后Redux存储的分类数据丢失,触发重复请求。
修复:在CategoryReducer中新增HYDRATE动作的处理逻辑:
// Reducer File 新增引入HYDRATE import { HYDRATE } from "next-redux-wrapper"; import * as t from '../types'; const initialState = { doc:null } const CategoryReducer = (state = initialState, action) =>{ console.log('reducer action', action.type); // 新增HYDRATE处理,合并服务端与客户端状态 if (action.type === HYDRATE) { return { ...state, ...action.payload.CategoryReducer } } switch (action.type){ case t.LOAD_CATEGORY: console.log('slots actions',action); return({...state, doc:action.value}) default: return state; } } export default CategoryReducer;
2. useEffect依赖项缺失
你当前Navbar组件的useEffect依赖数组为空,只会在组件首次挂载时执行一次判断,即使Redux中的loadCategory后续更新也不会重新触发校验。需要把loadCategory加入依赖数组:
useEffect(() => { if(loadCategory===null){ console.log('navbar loading funciton'); loadCategoryFunation(); } }, [loadCategory]); // 新增loadCategory作为依赖
3. Action存储逻辑错误
你当前接口请求成功后,存入Redux的是调用接口时传的type参数,不是后端返回的真实分类数据,会导致后续读取不到正确的分类列表,修复:
export const loadCategoryApi = (type) => dispatch => { axios.post(Constants.getCategories,type) .then(function (response) { console.log(response); if(response && response.data && response.data.status==="200"){ dispatch({ type: t.LOAD_CATEGORY, value: response.data.data // 替换为后端返回的真实分类数据字段 }); } else if(response && response.data && response.data.status==="404"){ alert('Someting went wrong'); } }) }
可选优化:配置客户端状态持久化
如果你的next-redux-wrapper版本≥7.0,可以在创建wrapper时增加序列化配置,避免客户端重复创建store实例:
// Store file 修改 export const wrapper = createWrapper(makeStore, { debug: false, serializeState: (state) => JSON.stringify(state), deserializeState: (state) => JSON.parse(state), });
内容的提问来源于stack exchange,提问作者Pooja
相关产品推荐
相关产品推荐

