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

React状态中嵌套数组更新问题:features数组无法正常更新

解决React嵌套数组状态更新失效问题

你更新嵌套数组features的方式存在两个核心问题:

  1. 循环中拿到的feature是数组元素的值拷贝,直接给feature赋值根本不会修改原数组里的元素;
  2. 即使修改了数组元素,若没有改变features数组的引用,React的浅比较机制会认为状态未变化,不会触发组件重渲染。

对比你能成功更新price的场景,是因为你直接修改了对象的属性值,之后通过展开plans数组创建了新的数组引用,触发了重渲染,但这种直接修改状态对象的写法其实违反了React状态不可变的原则,不推荐使用。

正确的嵌套数组更新写法

推荐使用函数式更新,同时严格遵循状态不可变原则,创建新的数组和对象副本:

{plans[0].features.map((feature, index) => (
  <div key={index}>
    <input
      value={feature}
      onChange={(e) => {
        setPlans(prevPlans => {
          // 复制整个plans数组,避免修改原状态
          const newPlans = [...prevPlans];
          // 复制第一个plan对象
          const updatedPlan = {...newPlans[0]};
          // 复制features数组并修改对应索引的元素
          updatedPlan.features = updatedPlan.features.map((item, i) => 
            i === index ? e.target.value : item
          );
          // 将修改后的plan放回数组
          newPlans[0] = updatedPlan;
          return newPlans;
        });
      }}
    />
  </div>
))}

规范你的price更新逻辑

同样按照不可变原则修正之前的price更新代码,避免直接修改状态对象:

onChange={(e) => {
  setPlans(prevPlans => {
    const newPlans = [...prevPlans];
    const updatedPlan = {...newPlans[0]};
    // 复制price对象并修改指定属性
    updatedPlan.price = {...updatedPlan.price, Annually: e.target.value};
    newPlans[0] = updatedPlan;
    return newPlans;
  });
}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:57:29