You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中调用store.dispatch触发action时Redux Store被重置如何解决?

问题原因

你当前遇到的store其余数据被清空问题和store.dispatch的调用方式无关,完全是reducer的实现逻辑错误导致的:

  1. 你贴出的HELP_ME分支仅声明了局部变量,没有返回新的state对象,且没有合并原有state的所有属性
  2. 初始状态存在拼写错误,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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:06:04