我想从 data
中删除一个实体(它是对象 someData
中的 List)。我在我的 reducer 中使用不可变 js 的 fromJS
来保持状态不可变
我尝试使用 updateIn、deleteIn、update、removeIn
以及我能在 immutable-js 上找到的任何东西。但这对我不起作用。很可能我以错误的方式使用了这些功能。
import { fromJS, updateIn } from 'immutable';
import * as type from './constants';
export const initialState = fromJS({
someData: [],
loading: true,
});
function someReducer(state = initialState, action) {
switch (action.type) {
case type.DELETE_SINGLE_ENTITY:
updateIn(state, ['someData', 'data'], val =>
val.filter(x => x.id !== action.id),
);
return state;
default:
return state;
}
}
export default someReducer;
//example someData
/*
{
date: "",
data: [
{
"id": "1",
"machine_type": "xyz",
"created_time": "2019-06-18T10:36:60Z",
...
},
{
"id": "22",
"machine_type": "abc",
"created_time": "2019-06-20T10:36:60Z",
...
},
{
"id": "2",
"machine_type": "kjhkh",
"created_time": "2019-06-11T12:36:60Z",
...
}
]
}
*/
我想删除与操作中传递的 id 匹配的实体。
删除之前 state.get('someData')
的输出在上面的例子中。当我键入 state.get
时,我的预期输出(当 action.id
为 2 时)应该是:
{
date: "",
data: [
{
"id": "1",
"machine_type": "xyz",
"created_time": "2019-06-18T10:36:60Z",
...
},
{
"id": "22",
"machine_type": "abc",
"created_time": "2019-06-20T10:36:60Z",
...
}
]
}
最佳答案
终于!知道了! 这个:
return updateIn(state, ['someData', 'data'], val =>
val.filter(x => x.id !== action.id),
);
而不是这个:
updateIn(state, ['someData', 'data'], val =>
val.filter(x => x.id !== action.id),
);
return state;
以前我认为 updateIn 会更新状态本身,但它不会返回更新后的对象。所以只返回 updateIn 就可以了。
关于javascript - 如何删除 reducer 内 immutable-js 中的嵌套状态对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639898/