const initialState = {
arr: [
{
name: "Chicken",
grade: "A",
quantity: 0
},
{
name: "Mutton",
grade: "B",
quantity: 0
},
{
name: "Sandwich",
grade: "A-Plus",
quantity: 0
}
]
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_QUANTITY:
return {
...state,
arr: {
...state.arr,
[state.arr[action.index]]: {
...state.arr[action.index],
[state.arr[action.index][0].quantity]:
[state.arr[action.index][0].quantity] + 1
}
}
};
default:
return state;
}
};
我正试图不变地更新数量。每次我点击一个按钮,数量应该增加1.我写的上述代码是错误的(因此在这里发布查询)。如果有人能告诉我出错的地方并指出正确的方向,我会很感激。
我期待的最终输出是:
arr: [
{
name: "Chicken",
grade: "A",
quantity: 1 // Updated value
},
{
name: "Mutton",
grade: "B",
quantity: 0
},
{
name: "Sandwich",
grade: "A-Plus",
quantity: 0
}
]
有一些东西不适用于您当前的代码。您的初始状态将arr
定义为数组,但您的reducer将返回Object。此外,当您尝试访问quantity
中对象的arr
键时,您使用的是另一个与您的数据结构不匹配的[0]
索引访问器。
我还建议你组合reducer(使用combineReducers),以便更容易跟踪数据结构。通过组合Reducer,您可以处理数据结构的各个级别,而无需担心整个结构。此外,使用扩展运算符可以很好地处理对象,但是在操作数组时,像map
这样的函数有时会更清晰。
像这样的东西会做你需要的:
const arr = (state = initialState.arr, action) => {
switch (action.type) {
case actionTypes.ADD_QUANTITY:
return state.map((element, i) => {
return i === action.index ? {...element, quantity: element.quantity + 1} : element;
});
default:
return state;
}
}
const rootReducer = combineReducers({arr});