Redux Reducer中按Key向数组追加元素的实现方法
Got it, let's tackle this Redux reducer scenario. The goal is to safely update your state—either appending an element to an existing array tied to a PersonId, or creating a new entry with that PersonId and a fresh array containing the element. Remember, Redux reducers must be pure functions, so we never mutate the original state directly.
Step-by-Step Implementation
First, let's assume your state has an object structure where keys are PersonIds and values are arrays of elements:
// Initial state example const initialState = {};
And your action will look something like this (make sure to define a clear action type):
// Sample action { type: 'APPEND_ELEMENT_TO_PERSON', personId: 'person_123', element: { id: 'elem_456', name: 'New Element' } }
Now here's the reducer code that handles this logic:
function personElementsReducer(state = initialState, action) { switch (action.type) { case 'APPEND_ELEMENT_TO_PERSON': // 1. Get the current array for the PersonId (or empty array if it doesn't exist) const currentElements = state[action.personId] || []; // 2. Create a new array with existing elements + the new element (no mutation!) const updatedElements = [...currentElements, action.element]; // 3. Return a new state object with the updated entry return { ...state, [action.personId]: updatedElements }; default: // Always return the original state for unhandled actions return state; } }
Key Notes to Remember
- Immutability is critical: We use the spread operator (
...) to create new arrays and state objects instead of modifying the original. This ensures Redux detects the state change correctly. - Handling missing PersonIds: The
|| []fallback ensures we never try to append toundefinedif thePersonIdisn't in the state yet. - Computed property names:
[action.personId]lets us dynamically set the key in the new state object based on the action'spersonId.
Bonus: Appending Multiple Elements at Once
If your action needs to add multiple elements instead of one, just adjust the updatedElements line to spread the incoming array:
// For actions with an array of elements const updatedElements = [...currentElements, ...action.elements];
That's it! This approach keeps your reducer clean, follows Redux best practices, and handles both existing and new PersonId entries smoothly.
内容的提问来源于stack exchange,提问作者Sam

