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
mapcreates a brand new array, and spreading...itemcreates 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.payloadintotargetIdandnewTitlemakes 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
相关产品推荐
相关产品推荐

