我是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
}
]});
那麼我會在'action.fruits.map()'的大括號之前返回'actionFruit'?我試過了,減速器還沒有更新狀態。 –