首页 > 解决方案 > 使用 immutable.js 时如何将 update 更改为 updateIn

问题描述

我试图通过使用 immutable.js 使我的代码整洁。

但我不知道如何将更新替换为updateIn。请帮我。

[SET_COLOR]: (state, action) => {
  const counters = state.get("counters");
  const { color, index } = action.payload;

  return state.set(
    "counters",
    counters.updateIn([index, "color"], color => /*I got stuck here*/ )
  );
}

我试过 {color}, ({color}), color, color = color...

这是原始的。

const initialState = Map({
  counters: List([
    Map({
      number: 0,
      color: "black"
    })
  ])
});

(...)

[SET_COLOR]: (state, action) => {
  const counters = state.get("counters");
  const { color, index } = action.payload;

  return state.set(
    "counters",
    counters.update(index, counter => counter.set("color", color))
  );
},

标签: javascriptreduximmutable.js

解决方案


您应该尝试setIn

[SET_COLOR]: (state, action) => {
  const { color, index } = action.payload;

  return state.setIn(["counters", index, "color"], color);
}

updateIn仅当更新的值取决于位于提供给 的路径上的当前值时才有用updateIn。例如:

const immutableObject = Immutable.fromJS({ outerProp: { innerCount: 1 } }); 
immutableObject.updateIn(['outerProp', 'innerCount'], count => count + 1);

推荐阅读