如何将reducer case函数更改为不可变的js

时间:2018-11-21 16:37:05

标签: javascript reactjs react-redux immutable.js

我有一个代码来更新对象的计数值。现在我需要将其转换为immutable.js。我对immutable.js非常陌生。因此,如何将这段代码转换为immutable.js格式。

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;

但是在执行此操作时,我无法更新状态。我正在获取初始状态,但我不知道如何更新它。

预先感谢

2 个答案:

答案 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()

阅读:https://facebook.github.io/immutable-js/docs/#/Map

答案 1 :(得分:0)

  

返回state.setIn(['ingredients',action.ingredientName],)逗号后如何在此处提供更新选项。我给了++ 1,但我无法更新

return state.setIn(['ingredients',action.ingredientName], state.getIn(['ingredients',action.ingredientName]) + 1)