Redux 为什么不是';我的老板不更新我的商店吗?
我是redux新手,我正在尝试创建一个单独的redux应用程序。我遇到的问题是我的reducer无法更新我的商店。如果我对减速机中的存储进行变异,那么我会看到我的变化。我知道这是不好的做法,所以我尝试在不改变它的情况下更新它,但是当我看到控制台时。我看不到国家的变化。有人能帮我弄清楚为什么减速机没有更新商店吗 这是我的行动:Redux 为什么不是';我的老板不更新我的商店吗?,redux,immutability,Redux,Immutability,我是redux新手,我正在尝试创建一个单独的redux应用程序。我遇到的问题是我的reducer无法更新我的商店。如果我对减速机中的存储进行变异,那么我会看到我的变化。我知道这是不好的做法,所以我尝试在不改变它的情况下更新它,但是当我看到控制台时。我看不到国家的变化。有人能帮我弄清楚为什么减速机没有更新商店吗 这是我的行动: store.subscribe(() => { console.log("store changed", store.getState()); }); 这是我的
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;
}
下面是我的调度员示例(我创建了两个执行相同操作的调度员):
我看到的一个问题是,您实际上没有返回
action.fruits.map()
的结果。如果不使用花括号,箭头函数允许您省略return
关键字,但一旦添加了花括号,您就可以像正常情况一样启动函数体,并且由您显式返回某些内容
另外,从风格上讲,我建议将减速器的初始状态定义为一个单独的变量:
const initialState = [ /* fruits here */];
const fruitReducer = (state = initialState, action) => {
// reducer logic here
}
看起来您的嵌套更新逻辑是正确的,但是您可能还需要阅读Redux文档的部分。我发现,通过编写中间件的方式可以实现这一点。例如,我以前有:
const store = createStore(
rootReducer,
applyMiddleware(epicMiddleware),
composeEnhancers(applyMiddleware(...middleware))
)
然而,似乎double-apply中间件让redux变得暴躁,并且它不会从rootReducer捕获新的状态更新,而只是从epicMiddleware(这是一个从副作用触发操作/还原程序的奇特的东西)
将我的epicMiddleware
移动到我的applyMiddleware(…中间件)
调用解决了问题。也就是说,更新到以下工作:
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(...middleware)) // epicMiddleware is now in the `middleware` array
)
这可能不是您的问题,但这是导致您描述的症状的一个原因。因此,在
action.fruits.map()
上的右括号之前,我是否会返回actionFruit
?我试过了,但减速器仍然没有更新状态。
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(...middleware)) // epicMiddleware is now in the `middleware` array
)