import * as actionTypes from '../actions/actionTypes';
const initialState={
ingredients: {
salad:0,
meat:0,
cheese:0,
},
totalprice:40
}
const ingredientCost = {
cheese:20,
meat:30,
salad:10,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_INGREDIENT:
return {
...state,
ingredients:{
...state.ingredients,
[action.ingredientName] : state.ingredients[action.ingredientName]+1
},
totalprice: state.totalprice + ingredientCost[action.ingredientName],
};
case actionTypes.REMOVE_INGREDIENT:
return {
...state,
ingredients:{
...state.ingredients,
[action.ingredientName] : state.ingredients[action.ingredientName]-1,
},
totalprice: state.totalprice - ingredientCost[action.ingredientName],
};
default:
return state;
}
};
export default reducer;
我试图将代码更改为不可变格式:
import * as actionTypes from '../actions/actionTypes';
import Immutable from 'immutable';
const initialState=Immutable.fromJS({
ingredients: {
salad:0,
meat:0,
cheese:0,
},
totalprice:40
})
const ingredientCost = {
cheese:20,
meat:30,
salad:10,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADD_INGREDIENT:
return state.ingredients[action.ingredientName].merge(state.ingredients[action.ingredientName]+1)
case actionTypes.REMOVE_INGREDIENT:
return {
...state,
ingredients:{
...state.ingredients,
[action.ingredientName] : state.ingredients[action.ingredientName]-1,
},
totalprice: state.totalprice - ingredientCost[action.ingredientName],
};
default:
return state;
}
};
export default reducer;
但是在执行此操作时,我无法更新状态。我正在获取初始状态,但我不知道如何更新它。
预先感谢
答案 0 :(得分:0)
由于t(result)
sd mean
mat1 1.677669 25.67452
mat2 1.677669 25.67452
mat3 1.572029 24.31933
是不可变的对象,您不能使用initialState
,应该使用
state.ingredients
/ state.set()
或state.setIn()
/ state.update()
或state.updateIn()
/ state.merge()
答案 1 :(得分:0)
返回state.setIn(['ingredients',action.ingredientName],)逗号后如何在此处提供更新选项。我给了++ 1,但我无法更新
return state.setIn(['ingredients',action.ingredientName], state.getIn(['ingredients',action.ingredientName]) + 1)