【问题标题】:Redux reducer state not updatingRedux reducer 状态未更新
【发布时间】:2018-08-04 12:36:33
【问题描述】:

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,并且有 + 和 - 按钮来增加,减少该产品的数量。 On - 单击我想减少数量,如果计数减少到 0,我也想从我的 redux 状态中删除这个产品。 现在我有我的减速器,首先我检查计数是否为 1,然后删除产品本身,否则仅减少计数。我正在返回状态,但它没有更新 DOM

谁能帮忙解决一下我在返回状态时做错了什么。

谢谢

【问题讨论】:

    标签: redux return react-redux state reducers


    【解决方案1】:

    您似乎忘记在 else 块中包含赋值语句。

      } 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)
    

    【讨论】:

      【解决方案2】:

      看起来你是在直接操作状态,这会导致 React 出现问题。您应该复制状态 let chosenIds = Object.assign({}, state);,而不是 let chosenIds = state;。然后你就可以随意操作chosenIds了。

      【讨论】:

        猜你喜欢
        • 2021-01-08
        • 2019-07-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-21
        • 1970-01-01
        • 2017-08-08
        • 2019-07-18
        • 2017-11-27
        相关资源
        最近更新 更多