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

如何在Next.js+TypeScript中用useReducer更新嵌套对象状态?

替换嵌套对象状态的正确写法

你的问题出在reducer里对companyProfile的更新逻辑——你错误地把每个字段都赋值为整个payload对象,而不是直接用payload替换整个companyProfile。

修改后的Reducer代码

const Reducer = (state: initialStateAttributes, action: actionAttributes) => {
  switch(action.type) {
    case actionEnum.COMPANY_PROFILE_DATA:
      return {
        ...state, // 保留userInfo、isLoading等顶层状态不变
        companyProfile: action.payload // 直接替换整个companyProfile对象
      };
    // 其他case逻辑...
    default:
      return state; // 必须保留default分支,避免状态丢失
  }
};

关键说明

  1. 直接替换而非逐个赋值:因为你需要完全覆盖companyProfile的所有值,所以不需要用...state.companyProfile展开旧对象——这会保留旧字段,而我们要的是全量替换。
  2. 类型匹配检查:确保axiosGetCompanyProfile类型和initialState里的companyProfile结构完全一致,TypeScript才不会报错。比如:
    type axiosGetCompanyProfile = {
      companyDescription?: string;
      companyLogo?: string;
      companyLogoPublicId?: string;
      companyName?: string;
      owner?: string;
      _id?: string;
    };
    
  3. 处理多余字段(可选):如果API返回的字段比companyProfile定义的多,可以手动解构只保留需要的字段:
    case actionEnum.COMPANY_PROFILE_DATA:
      const { companyDescription, companyLogo, companyLogoPublicId, companyName, owner, _id } = action.payload;
      return {
        ...state,
        companyProfile: { companyDescription, companyLogo, companyLogoPublicId, companyName, owner, _id }
      };
    

这样修改后,dispatch action时,companyProfile就会被API返回的完整数据替换,而不是每个字段都赋值为整个payload对象。

内容的提问来源于stack exchange,提问作者kingNodejs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:17:46