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

React/Redux中如何更新Store数组内的对象?

How to Update an Object in an Array with React/Redux

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()?: The map() method returns a brand-new array, so we never touch the original state.insiders array. 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 in updatedInsider will overwrite the original values—exactly what we want for an update.
    • { ...state, insiders: updatedInsiders } creates a new state object, replacing only the insiders property while preserving the rest of your state.
  • Unique Identifier: We use insider.id === updatedInsider.id to target the right object. If your insiders don’t have an id, use another unique property (like email or employeeNumber)—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] = updatedInsider or insider.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:09:02