我是 Redux 的新手,我想知道是否可以根据 initState 中的另一种状态来更改一种状态?
const initState = {
expenses:[
{ key: '1', sum: '100'},
{ key: '2', sum: '200'},
{ key: '3', sum: '300'}
],
total: 0 // I want here total sum from state above (100+200+300)
}
// let totalSum = initState.expenses.reduce((prev,next) => prev + Number(next.sum),0);
// console.log(totalSum)
=> 在这里我看到了总数,但是如果我把它放在 initState 里面我什么都没有
对我来说,其他问题是 rootReducer 中的总状态更改。我不明白为什么我的变量 let totalSum 在这两种情况下都不起作用?如果我提交其中一个,它适用于一种情况,如果两者都未提交,那么我得到错误 totalSum 已经被声明。
const rootReducer = (state = initState, action) => {
switch(action.type){
case 'DELETE_COST':
let newExpenses = state.expenses.filter(cost => {
return action.key !== cost.key
})
// let totalSum = state.expenses.reduce((prev,next) => prev + Number(next.sum),0);
return {
...state,
total: totalSum,
expenses: newExpenses
}
case 'ADD_COST':
let totalSum = state.expenses.reduce((prev,next) => prev + Number(next.sum),0);
return {
...state,
total: totalSum,
expenses: [action.cost, ...state.expenses]
}
default:
return state;
}
}
export default rootReducer;
有什么建议么?我想重复一遍我是新来的:)