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

React Native:如何在Reducer中指定修改数组项(使用Immutability helpers)

Fixing Redux Reducer to Update Item by ID

Hey there! I see exactly what's going on here—your current reducer is always targeting the first item in the array instead of looking up the specific entry by its id. Let's get this sorted out properly, while keeping Redux's immutability rules in mind.

The Core Issue & Solution

In Redux, you can't mutate the original state directly. Instead, you need to create a new array where only the matching item gets updated. Here's how to adjust your reducer:

const initialState = [
  { id: 1, title: "some title" },
  { id: 2, title: "some other title" }
];

const yourReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'change_title': {
      // Destructure the payload to get the target ID and new title
      const [targetId, newTitle] = action.payload;
      
      // Use map to create a new array (avoids mutating the original state)
      return state.map(item => {
        // If this is the item we want to update, return a new object with the updated title
        if (item.id === targetId) {
          return { ...item, title: newTitle };
        }
        // For all other items, return the original (no changes)
        return item;
      });
    }
    // Always handle the default case to return the original state
    default:
      return state;
  }
};

Key Things to Note

  • Immutability: Using map creates a brand new array, and spreading ...item creates a new object for the updated entry. This ensures we never modify the original state directly, which is critical for Redux to track changes correctly.
  • Targeted Update: By checking item.id === targetId, we only update the exact item that matches the ID from your action payload.
  • Clear Payload Destructuring: Breaking action.payload into targetId and newTitle makes the code easier to read and maintain.

If you were previously doing something like modifying the first item directly (e.g., state[0].title = newTitle), that's why it was always changing the first entry—this approach fixes that by targeting the ID instead of index.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:12:35