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

如何使用useImmer动态修改WritableDraft类型的Person属性?

解决useImmer动态更新对象属性不生效的问题

你的代码里核心问题是误用了map遍历Object.entries——map是用于生成新数组的方法,不会主动执行遍历逻辑里的赋值副作用,换成forEach就能让赋值操作正常执行。

另外,TypeScript会因为property是string类型,无法直接匹配Person的键,需要添加类型断言解决类型报错问题。

修正后的代码如下:

type Person = {
  name?: string;
  age?: number;
  // 其他可选属性
};

const [person, updatePerson] = useImmer<Person>({
  name: 'Michel',
  age: 33,
  // 其他属性的初始值
});

function replacePerson(person: Person) {
  updatePerson((draft) => {
    // 替换map为forEach,确保赋值逻辑执行
    Object.entries(person).forEach(([property, value]) => {
      // 类型断言,告知TypeScript该属性属于Person的键
      draft[property as keyof Person] = value;
    });
  });
}

如果你的需求是直接用传入的对象完全替换原状态,还可以用更简洁的写法:

function replacePerson(person: Person) {
  updatePerson(() => person);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:45:31