简体   繁体   中英

React + immutable.js: merge Map into List of Maps to update state

I'm trying out immutable.js in my new React project, but I'm having a blackout at adding a Map to an existing List of Maps in my state.

I would previously have written (using Arrays and Objects):

this.setState({
  objectsArray: [...this.state.objectsArray, newObject];
})

But I'm struggling to find the proper equivalent with immutable.js. I've tried things along the lines of this, but with no success:

state.get('mapsList').merge(newMap);

I'm finding plenty of examples on the web merging Lists and merging Maps, but I'm having a List of Maps, and the official docs on immutable Lists are not exactly elaborate.

Links to resources and best practices regarding React/Redux state operations appreciated as well, thank you!

Your "old" code creates a new array with the same objects that already existed, plus a new object.

As far as I can see, Immutable's List#push does the same thing:

push()

Returns a new List with the provided values appended, starting at this List 's size .

 push(...values: Array<T>): List<T> 

So:

this.setState(({mapsList}) => {
    return {mapsList: mapsList.push(newMap)};
});

Side note: I'm using the callback version of setState because you're not allowed to do what your old code did. If you're setting new state based on existing state, you must use the callback; details .

you need to update the list with

state = state.updateIn(['mapsList'], function(list) { return list.push(newMap); })

that will update the mapsList List with the new newMap

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