Next.js中调用store.dispatch触发action时Redux Store被重置如何解决?
问题原因
你当前遇到的store其余数据被清空问题和store.dispatch的调用方式无关,完全是reducer的实现逻辑错误导致的:
- 你贴出的
HELP_ME分支仅声明了局部变量,没有返回新的state对象,且没有合并原有state的所有属性 - 初始状态存在拼写错误,
reducerVar的初始值fase应为false
修复方案
修改reducer逻辑,Redux要求reducer返回全新的state对象时,必须先解构保留原有state的所有属性,再覆盖需要更新的字段,修正后的代码如下:
const initialState = { // 修正拼写错误 reducerVar: false, otherExistingVar: {}, otherExistingVarTwo: null, otherExistingThree:null, otherExistingVarFour: false, }; const myReducer = (state = initialState, action) => { switch (action.type) { case HELP_ME: { // 解构原有state所有属性,仅覆盖需要更新的字段 return { ...state, reducerVar: action.payload } } default: return state } } export default myReducer
额外说明
你当前在组件外引入单例store调用dispatch的写法本身是合规的,在Next.js环境下只要保证引入的store是同一个客户端单例,执行效果和组件内调用useDispatch完全一致,无需更换实现方式。
如果使用了服务端渲染能力,需要注意区分服务端和客户端的store实例:服务端每次请求生成独立的store实例,客户端复用同一个实例,避免跨请求的状态污染。
内容的提问来源于stack exchange,提问作者benjamin852
相关产品推荐
相关产品推荐

