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

在Redux Reducer中使用splice遇组件不更新问题求助

Fixing Redux Component Update Issue When Removing a Recipe from Favorites

Hey Davide, I totally get why this is confusing—you can see the element is gone in the console, but the component won’t update. Let’s break down what’s happening and fix it!

The Root Problem: You’re Mutating the Original State

Redux relies on immutable state updates to detect changes and trigger component re-renders. When you do let favourite = state.favourite, you’re just creating a reference to the original favourite object in state, not a copy. Then using splice() directly modifies the original recipes array—this mutates the existing state instead of creating a new one. Even though the array content changes, Redux doesn’t pick up on it because the reference to the array/object hasn’t changed.

Here’s How to Fix It

We need to create copies of the parts of state we’re modifying, so we return a brand new state object that Redux can detect as a change. Here are two solid approaches:

Approach 1: Copy the Array First (Using Spread Operator)

First make a copy of the recipes array, modify the copy, then build a new state object with the updated array:

if (action.type === "REMOVE_RECIPE_FROM_FAV") {
  // Create a copy of the recipes array
  const updatedRecipes = [...state.favourite.recipes];
  // Modify the copied array (this doesn't touch the original state)
  updatedRecipes.splice(action.data, 1);
  
  return {
    ...state, // Copy all existing top-level state properties
    favourite: {
      ...state.favourite, // Copy other favourite properties (wines, products)
      recipes: updatedRecipes // Replace with our modified array
    }
  };
}

Approach 2: Use filter() (Cleaner, Immutable Alternative)

Instead of splice(), use filter() which returns a new array automatically, no need to manually copy first. This is my go-to for removing items since it’s a pure function:

if (action.type === "REMOVE_RECIPE_FROM_FAV") {
  return {
    ...state,
    favourite: {
      ...state.favourite,
      // Filter out the recipe at the index from action.data
      recipes: state.favourite.recipes.filter((_, index) => index !== action.data)
    }
  };
}

(Note: If later you switch to removing by recipe ID instead of index, just replace index !== action.data with recipe.id !== action.data.id—this approach scales better!)

Why This Works

By creating new copies of the recipes array and the favourite object, we’re giving Redux a fresh reference to check against. When Redux sees the new state object/array references, it knows something changed and tells your components to re-render with the updated data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:37:36