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

如何使用Context API更新状态对象数组中指定索引对象的属性值

对应reducer实现方案

首先给出标准不可变更新的reducer代码:

const reducer = (state, action) => {
  switch (action.type) {
    // 直接使用你定义的SET_SPEED常量即可
    case SET_SPEED:
      const targetIndex = action.payload.respond;
      // 可选:增加索引合法性校验,避免越界报错
      if (targetIndex < 0 || targetIndex >= state.cars.length) {
        return state;
      }
      // 1. 复制原cars数组生成新数组
      // 2. 遍历判断索引,匹配到的项复制原对象后修改speed属性
      const newCars = state.cars.map((car, index) => 
        index === targetIndex ? { ...car, speed: car.speed + 1 } : car
      )
      // 3. 返回全新的状态对象
      return {
        ...state,
        cars: newCars
      };
    default:
      return state;
  }
}

核心注意点

  • 所有状态更新必须遵循不可变原则:不能直接修改原state、原cars数组、数组内的原对象,否则会出现状态变更后视图不刷新的问题
  • 上面用map的写法是更简洁的函数式写法,也可以用数组下标替换的方式实现,效果完全一致:
// 替换上面newCars生成逻辑
const newCars = [...state.cars];
newCars[targetIndex] = {
  ...newCars[targetIndex],
  speed: newCars[targetIndex].speed + 1
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:45:03