简体   繁体   中英

immutablejs (react/redux) , “push” into state with immutable

In my react/redux app, I am setting states in my reducers using something like this :

 state.set('search', myResults);

the state is an immutablejs Map() . The format of the object when toJS() is run on it (no longer an immutable object) is like so :

 {
    results: { ..all results in here }
 }

So you'd have state.search.results .

and this works great, however I have a scenario where I need to "push" into the search part of this map. I was thinking merge would take care of this however it does not seem to work as I assumed it would. I have tried :

  state.mergeIn('search', singleResult);

as well as

 state.merge({ 'search': singleResult });

neither seem to be working. The intended result is to have that single result pushed into the state Map() (and not overriding it like with .set ). So the desired result would end up looking like this :

 {
    results: { singleResult pushed or merged into here with other results }
 }

I am unsure how to do this with immutablejs, any advice would be greatly appreciated. Thanks!

You need to use update for this. Merging does not concat arrays together in the key.

state.update('search', search => search.concat(singleResult));

Also be aware that if search contains a normal JS array - then the array itself is still an mutable data structure. Immutable.JS doesn't do deep conversion of datatypes unless you use fromJS().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM