我将react + redux与Immutable一起使用,如何使用Immutable删除List中的某些元素?
dispatch(removeRoom('102'))
然后,我发送一个动作,删除{room: 102}
的某个空间,但我怎样才能简单地删除{{1}}与Immutable?
答案 0 :(得分:1)
首先,编写一个函数findRoomPath
以查找您所在州的房间路径。
并使用deleteIn
删除此路径中的值。
var roomPath = findRoomPath(state, 101);
state = state.deleteIn(roomPath);
var state = Immutable.fromJS({
floor: [
{
floor: '1',
rooms: [
{
room: '101'
}
]
},
{
floor: '2',
rooms: [
{
room: '104'
}
]
}
]
});
function findRoomPath(state, room) {
var keyPath = ['floor'];
state
.get('floor')
.find((v, k1) => {
return v
.get('rooms')
.find(function(v, k2) {
if (+v.get('room') === +room) {
keyPath.push(k1, 'rooms', k2);
return true;
}
});
});
return keyPath.length > 1 ?
keyPath :
null;
}
function deleteRoom(state, room) {
var roomPath = findRoomPath(state, room);
return (roomPath) ?
state.deleteIn(roomPath) :
state;
}
console.log(deleteRoom(state, 101).toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
答案 1 :(得分:0)
我必须说,我对Immutable不太熟悉,但这有点干净。我强烈建议你重新考虑一下你所在州的结构!你将免于经历许多痛苦!
export default function list(state = initialState, {type, payload}) {
switch (type) {
//remove some room
case REMOVE_ROOM:
return removeRoom(state, payload);
default:
return state;
}
};
const removeRoom (state, roomToRemove) => {
const floor = state.get('floor').map(floor => {
const rooms = floor.get('rooms').filter(room => room.get('room') !== roomToRemove)
return floor.merge({rooms});
})
return state.merge({floor});
};