使用 immutable.js 时如何将 update 更改为 updateIn
How can I change update into updateIn when I use immutable.js
我正在尝试使用 immutable.js 使我的代码整洁。
但是我不知道怎么把update替换成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))
);
},
您应该尝试 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);
我正在尝试使用 immutable.js 使我的代码整洁。
但是我不知道怎么把update替换成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))
);
},
您应该尝试 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);