[英]immutablejs (react/redux) , “push” into state with immutable
[英]Changing ImmutableJS nested object with List and return whole state (Redux)
我的狀態是嵌套的不可變的東西:
const state = Map({ counter: 0,
people: List([
Map({name: "John", age: 12, etc...}),
Map({name: "Jim", age: 13, etc...}),
Map({name: "Jack", age: 21, etc...})
])
});
因此,我有一個地圖,其中包含一個計數器和地圖列表。 我在這里簡化了事情,但是說我想在我的減速器中更改John的某些屬性。
現在我正在做這樣的事情:
var newState = state
.get('people') //get the list
.get(action.payload.pos) //pos is an integer, & describes the position of the object in the List
.set('name', action.payload.name)
.set('age', action.payload.age);
我的問題是我不知道如何在John中設置屬性並返回整個狀態 ,所以我可以在我的reducer中返回它。 現在,我所獲得的只是我正在改變的一部分。
第二個問題是將所有這些記下來的很長的路要走。 我知道嵌套結構有一種語法,但是我在這里有一個List
,這種方法可以解決這個問題,所以我有些困惑。
您可以使用.findIndex
查找要更新的索引(如果您尚未擁有),然后在.updateIn
調用中使用該索引,並與.merge
一起使用以合並舊值和新值。
const state = new Immutable.Map({ counter: 0, people: new Immutable.List([ new Immutable.Map({name: "John", age: 12, otherVal: 'a'}), new Immutable.Map({name: "Jim", age: 13, otherVal: 'b'}), new Immutable.Map({name: "Jack", age: 21, otherVal: 'c'}) ]) }); const newValues = { name: 'Jones', age: 100}; // find index to update const indexToUpdate = state .get('people') .findIndex(person => person.get('name') == 'Jim'); // use .updateIn to perform a merge on the person of interest const newState = state.updateIn( ['people', indexToUpdate], person => person.merge(newValues) ); console.log( 'new state is:\\n', JSON.stringify(newState.toJS(), null, 2) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.2/immutable.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.