Redux还原状态不更新



import types from "../actions/types";
export default function(state = null, action) {
  switch (action.type) {
    case types.fetchCartProducts:
      return action.payload || false;
    case types.modifyCart:
      debugger;
      switch (action.payload.operation) {
        case "subtract":
          const index = action.payload.index;
          let isSingleCount = state[index] === 1;
          let chosenIds = state;
          if (isSingleCount) {
            chosenIds = chosenIds.filter(index => index != index);
          } else {
            [
              ...chosenIds.slice(0, index),
              { ...chosenIds[index], count: chosenIds[index].count - 1 },
              ...chosenIds.slice(index + 1)
            ];
          }
          return (
            chosenIds
          )
      }
    default:
      return state;
  }
}

{
          "Products": [
            {
              index: 1,
              name: "Shirt",
              price: 1.9,
              count: 2
            },
            {
              index: 2,
              name: "Jeans",
              price: 1.9,
              count: 2
            }
          ]
        }

我有一个反应组件,显示了购物车产品。购物车中的每种产品都是单独的div,并且具有 和 - 按钮以增加,减少该产品的NO。开启 - 单击我要减少数量,而且如果计数减少到0,我也想从我的redux状态中删除此产品。现在,我有了我的还原器,首先我要检查计数是否为1,然后删除产品本身,而仅减少计数。我正在返回国家,但没有更新DOM

任何人都可以在这方面提供帮助,我在返回状态时做错了什么。

谢谢

看起来您直接操纵状态,这将导致React中的问题。您应该复制状态let chosenIds = Object.assign({}, state);,而不是let chosenIds = state;。然后,您可以按照自己的意愿操纵chosenIds

看起来您忘了在Else Block中包含一个分配语句。

  } else {
       chosenIds = [
          ...chosenIds.slice(0, index),
          { ...chosenIds[index], count: chosenIds[index].count - 1 },
          ...chosenIds.slice(index + 1)
        ];
      }

您可以使用array.map来更新数组中的单个项目。

 chosenIds = state.map(item => item.index === index ? {...item, count: item.count - 1} : item)