我在 redux reducer 中有一个不可变对象作为我的状态,并且正在尝试将对象添加/更新到列表中。
这是我的减速器:
import { fromJS } from 'immutable'
const initialState = fromJS({
editable: true
})
export default (state = initialState, action) => {
switch(action.type) {
case 'CONTENT_MODE': {
return state.set('editable', action.editable ? false : true)
}
case 'UPDATE_CONTENT': {
return state.set(action.page, action.content)
// action.page = String
// action.content = {}
}
default: {
return state
}
}
}
我想将对象添加到页面键,但是如果它当前存在,请更新值。我已经尝试过 updateIn 和 add() 回调,但我对 immutable.js 还很陌生,不知道如何正确处理它。
set() 方法完全重写了“页面”值,而我需要推送该值并且仅在它存在时才设置,最终得到:
例子
const initialState = fromJS({
editable: true,
home: {
title: {
name: 'this is the name',
value: 'this is the value'
},
body: {
name: 'this is the name',
value: 'this is the value'
}
},
page1: {
title: {
name: 'this is the name',
value: 'this is the value'
},
body: {
name: 'this is the name',
value: 'this is the value'
}
}
})