为什么我的减速机没有更新我的商店?

时间:2017-05-09 15:43:57

标签: redux immutability

我是redux的新手,我正在尝试创建一个单独的redux应用程序。我遇到的问题是我的减速机不能更新我的商店。如果我要在减速机中改变商店,那么我会看到我的改变。我知道这是不好的做法,所以我试图更新它而不改变它,但是当我看到控制台时。我看到国家没有变化。有人可以帮我弄清楚减速机为什么不更新商店?

这是我的行动:

store.subscribe(() => {
  console.log("store changed", store.getState());
});

这是我的减速机:

const fruitReducer = function(state={
  fruits: [
    {
      "itemName": "banana",
      "price": 1.00,
      "quantityRemaining": 10
    },
    {
      "itemName": "apple",
      "price": 2.00,
      "quantityRemaining": 5
    },
    {
      "itemName": "raspberry",
      "price": 5.00,
      "quantityRemaining": 2
    },
    {
      "itemName": "kiwi",
      "price": 3.00,
      "quantityRemaining": 15
    },
    {
      "itemName": "pineapple,
      "price": 7.00,
      "quantityRemaining": 1
    },
    {
      "itemName": "strawberries",
      "price": 2.00,
      "quantityRemaining": 3
    }
  ]
}, action){
  if(action.type === "DEDUCT"){
    return Object.assign({}, state, {
      fruits: state.fruits.map((fruit, index) => {
        action.payload.map((actionFruit) => {
          if(fruit.itemName === actionFruit.itemName){
            let newQuantity = fruit.quantityRemaining - actionFruit.quantityRemaining;
            return Object.assign({}, fruit, {
              quantityRemaining: newQuantity
            });
          }
        });
        return fruit;
      })
    });
  }
  else
    return state;
}

下面是我的调度员的一个例子(我创建了两个做同样的事情):

store.dispatch({type: "DEDUCT", payload: [
  {
    "itemName": "banana",
    "quantityRemaining": 1
  },
  {
    "itemName": "apple",
    "quantityRemaining": 1
  },
  {
    "itemName": "strawberries",
    "quantityRemaining": 1
  }
]});

2 个答案:

答案 0 :(得分:0)

我发现的一个问题是您实际上并未返回action.fruits.map()的结果。箭头功能允许你省略return关键字,如果你不使用花括号,但是一旦你添加了curlies,你就像正常一样启动了一个函数体,它就是'由你决定明确归还。

另外,作为一个风格笔记,我建议将该reducer的初始状态定义为一个单独的变量:

const initialState = [ /* fruits here */];

const fruitReducer = (state = initialState, action) => {
    // reducer logic here
}

您的嵌套更新逻辑看起来是正确的,但您也可以阅读Redux文档的Structuring Reducers - Immutable Update Patterns部分。

答案 1 :(得分:0)

我发现这个可以以你构建中间件的方式发生。例如,我之前有:

const store = createStore(
  rootReducer,
  applyMiddleware(epicMiddleware),
  composeEnhancers(applyMiddleware(...middleware))
)

然而,似乎双重应用中间件使得redux脾气暴躁,并且它不会从rootReducer捕获新的状态更新,只是epicMiddleware(从副作用触发动作/减少器是一个奇特的事情)

epicMiddleware移至我的applyMiddleware(...middleware)来电解决了问题。也就是说,更新到以下工作:

const store = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(...middleware)) // epicMiddleware is now in the `middleware` array
)

这可能不是你的问题,但这可能会导致你所描述的症状。