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

RTK AsyncThunk中更新指定对象数据的问题求助

解决RTK中合并部分更新数据、保留未修改字段的问题

你当前的代码仅更新了basic_information.primary_information,既没处理user_profile的更新,也没有保留原有对象中未被接口返回的字段(比如Token、photo)。利用RTK内置的Immer,可以通过嵌套对象浅合并的方式实现需求,具体修改如下:

修改updatePrimaryInformation.fulfilled的处理逻辑

.addCase(updatePrimaryInformation.fulfilled, (state, action) => {
  state.loading = "succeeded";
  // 合并user_profile:保留原有Token,更新name
  state.data.user_profile = {
    ...state.data.user_profile,
    ...action.payload.user_profile
  };
  // 合并primary_information:保留原有photo,更新sex和age
  state.data.basic_information.primary_information = {
    ...state.data.basic_information.primary_information,
    ...action.payload.basic_information.primary_information
  };
})

逻辑说明

  • Immer允许你直接"修改"state对象,它会在后台自动生成不可变的新状态,无需手动创建深层副本。
  • 使用对象展开运算符...将原有字段与接口返回的更新字段合并:原有字段会被返回的同名字段覆盖,未被返回的字段(如Token、photo)则会被保留。
  • 如果你的数据结构后续可能更复杂,可以考虑使用递归合并工具函数,但对于固定结构的数据,手动合并更直观且性能更好。

完整的authenticateSlice片段(仅展示更新相关部分)

const authenticateSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // ...其他case(login、logout)保持不变
      //updatePrimaryInfo
      .addCase(updatePrimaryInformation.pending, (state) => {
        state.loading = "pending";
      })
      .addCase(updatePrimaryInformation.fulfilled, (state, action) => {
        state.loading = "succeeded";
        // 合并user_profile
        state.data.user_profile = {
          ...state.data.user_profile,
          ...action.payload.user_profile
        };
        // 合并primary_information
        state.data.basic_information.primary_information = {
          ...state.data.basic_information.primary_information,
          ...action.payload.basic_information.primary_information
        };
      })
      .addCase(updatePrimaryInformation.rejected, (state, action) => {
        state.loading = "failed";
        state.message = action.payload;
      });
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:53:18