Typescript 如何设置复杂/嵌套状态';使用ImmutableJS的Reducer上的属性?
目前,我将以下对象结构定义为存储的初始状态Typescript 如何设置复杂/嵌套状态';使用ImmutableJS的Reducer上的属性?,typescript,redux,immutability,immutable.js,Typescript,Redux,Immutability,Immutable.js,目前,我将以下对象结构定义为存储的初始状态 { counter: 0, messages: { newMessages: 25, inbox: 100 } } 这里我使用的是immutableJS,在我的reducer中,如果我想修改状态,我将实现如下内容: function myReducer(state: Map<string, any>, action): Map<string, any> { switch (action.type
{
counter: 0,
messages: {
newMessages: 25,
inbox: 100
}
}
这里我使用的是immutableJS,在我的reducer中,如果我想修改状态,我将实现如下内容:
function myReducer(state: Map<string, any>, action): Map<string, any> {
switch (action.type) {
case COUNTER_INCREMENT:
return state.set('counter', state.get('counter') + 1);
case INBOX_INCREMENT:
return state.set(xxxx, yyyy + 1);
}
return state;
}
但是,如果我们想修改复杂/嵌套属性,比如
messages.inbox
,该怎么办?xxxx
和yyyy
值应该是什么?Immutable提供了一个setIn
命令,您可以通过该命令提供嵌套路径和将该路径设置为的值
从:
没有直接为
setIn
提供示例,但我认为语义是相似的。可以找到它的文档。如果要为邮件设置新值。收件箱
,可以使用:
如果要根据当前值为
messages.inbox
设置新值,请使用:
state.set('counter', state.get('counter') + 1)
const { fromJS } = require('immutable')
const nested = fromJS({ a: { b: { c: [ 3, 4, 5 ] } } })
const nested2 = nested.mergeDeep({ a: { b: { d: 6 } } })
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 6 } } }
console.log(nested2.getIn([ 'a', 'b', 'd' ])) // 6
const nested3 = nested2.updateIn([ 'a', 'b', 'd' ], value => value + 1)
console.log(nested3);
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 7 } } }
const nested4 = nested3.updateIn([ 'a', 'b', 'c' ], list => list.push(6))
// Map { a: Map { b: Map { c: List [ 3, 4, 5, 6 ], d: 7 } } }
return state.setIn(['messages', 'inbox'], 101)
return state.updateIn(['messages', 'inbox'], inbox => inbox + 1