React/Redux中如何更新Store数组内的对象?
Hey there! Since you're only a week into React/Redux, let's break down how to properly update that array of insiders in your reducer—no overcomplicating things, promise.
First, a quick recap of a non-negotiable Redux rule: reducers must be pure functions. That means you can’t modify the original state directly; you have to return a new copy of state with your changes. This is critical because Redux relies on immutability to detect state updates and trigger component re-renders.
Step-by-Step Implementation
Assuming each insider object has a unique identifier (like an id—you’ll need this to target the exact object to update), here’s how your reducer case should look:
// Define your initial state first const initialState = { insiders: [] }; const insiderReducer = (state = initialState, action) => { switch (action.type) { case 'UPDATE_INSIDER': // Pull the updated insider from the action payload const { insider: updatedInsider } = action.payload; // Map over the insiders array to create a new array (no mutation!) const updatedInsiders = state.insiders.map(insider => { // Match the insider to update using its unique ID if (insider.id === updatedInsider.id) { // Return a NEW merged object: keep original properties, overwrite with updates return { ...insider, ...updatedInsider }; } // For all other insiders, return the original object (no changes needed) return insider; }); // Return a NEW state object with the updated insiders array return { ...state, insiders: updatedInsiders }; // Add other cases (like ADD_INSIDER, DELETE_INSIDER) here as needed default: return state; } };
Key Details to Wrap Your Head Around
- Why
map()?: Themap()method returns a brand-new array, so we never touch the originalstate.insidersarray. This keeps us compliant with pure function rules. - Spread Operator (
...):{ ...insider, ...updatedInsider }creates a new object, combining the original insider’s properties with the updated ones. Any properties inupdatedInsiderwill overwrite the original values—exactly what we want for an update.{ ...state, insiders: updatedInsiders }creates a new state object, replacing only theinsidersproperty while preserving the rest of your state.
- Unique Identifier: We use
insider.id === updatedInsider.idto target the right object. If your insiders don’t have anid, use another unique property (likeemailoremployeeNumber)—you need some way to match the object you want to update.
Common Mistakes to Avoid
- Don’t mutate the original state: Never do something like
state.insiders[index] = updatedInsiderorinsider.name = updatedInsider.name—this changes the original state directly, and Redux won’t pick up the update. - Don’t skip creating new objects/arrays: Always make copies instead of modifying existing ones. Immutability is your friend here!
That’s it! This approach follows Redux best practices and will correctly update your state while keeping everything immutable.
内容的提问来源于stack exchange,提问作者Chris Rutherford

