cyr*_*ilb 6 javascript reactjs redux
在我的名为“reducer_product_list”的减速器中,我有这个数组:
let initialState = [
{name: 'Article 1', price: 5, quantity: 10},
{name: 'Article 2', price: 15, quantity: 8},
{name: 'Article 3', price: 7, quantity: 15},
{name: 'Article 4', price: 9, quantity: 5},
{name: 'Article 5', price: 11, quantity: 100},
{name: 'Article 6', price: 23, quantity: 20},
]
Run Code Online (Sandbox Code Playgroud)
当我得到操作“ADD_TO_CART”时,我想减少所选对象的数量。有效载荷是这些对象之一。
我输入了上面的代码:
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_TO_CART':
initialState.map((product, i) => {
if (product.name === action.payload.name) {
initialState[i].quantity -= 1
return state;
}
});
default: return state
}
}
Run Code Online (Sandbox Code Playgroud)
如果我 console.log 我的初始状态,数量会减少,但在我呈现视图的容器中,数量保持不变。
感谢您的帮助。
Ngu*_*You 17
尝试这个:
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_TO_CART':
return state.map(product => {
if (product.name === action.payload.name) {
return {...product, quantity: product.quantity-1}
};
return product;
});
default: return state
}
}
Run Code Online (Sandbox Code Playgroud)
原因是您必须返回一个从当前状态派生的新状态对象,以根据请求的操作反映所需的更改。有关更多详细信息,请参阅Redux Reducers。
| 归档时间: |
|
| 查看次数: |
11740 次 |
| 最近记录: |