2017-05-09 96 views
0

我是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 
    } 
]}); 

回答

0

我看到的一个问题是,你实际上并没有返回action.fruits.map()的结果。如果不使用大括号,则可以使用箭头函数省略return关键字,但是一旦添加了curlies,就像正常情况一样启动了函数的主体,并且由您明确返回某些内容。

此外,作为一个文体记,我建议定义为减速机作为一个独立的变量的初始状态:

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

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

它看起来像你的嵌套更新逻辑是正确的轨道上,但是您可能想要阅读Redux文档的Structuring Reducers - Immutable Update Patterns部分。

+0

那么我会在'action.fruits.map()'的大括号之前返回'actionFruit'?我试过了,减速器还没有更新状态。 –

0

我发现这可以发生的方式你撰写你的中间件。举例来说,我以前有:

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

然而,却仿佛双重应用中间件做终极版脾气暴躁,而且它不会赶上从rootReducer,只是epicMiddleware(这是一个奇特的东西新的状态更新从副作用触发动作/减速器)。

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

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

它可能不是你的问题,但它是一个东西,可能会导致你描述的症状。