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

how to change the reducer case function to 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;

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

提前致谢

因为 initialState 是不可变对象,你不能使用 state.ingredients,你应该使用

  • state.set() / state.setIn()
  • state.update() / state.updateIn()
  • state.merge() / state.mergeIn()

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