Nested Objects

Immutable.Map wraps objects shallowly, meaning if you have an object with properties bound to mutable types then those properties can be mutated.

  1. let movie = Immutable.Map({
  2. name: 'Star Wars',
  3. episode: 7,
  4. actors: [
  5. { name: 'Daisy Ridley', character: 'Rey'},
  6. { name: 'Harrison Ford', character: 'Han Solo' }
  7. ],
  8. mpaa: {
  9. rating: 'PG-13',
  10. reason: 'sci-fi action violence'
  11. }
  12. });
  13. movie.get('actors').pop();
  14. movie.get('mpaa').rating = 'PG';
  15. console.log(movie.toObject());
  16. /* writes
  17. { name: 'Star Wars',
  18. episode: 7,
  19. actors: [ { name: 'Daisy Ridley', character: 'Rey' } ],
  20. mpaa: { rating: 'PG', reason: 'sci-fi action violence' } }
  21. */

To avoid this issue, use Immutable.fromJS instead.

  1. let movie = Immutable.fromJS({
  2. name: 'Star Wars',
  3. episode: 7,
  4. actors: [
  5. { name: 'Daisy Ridley', character: 'Rey'},
  6. { name: 'Harrison Ford', character: 'Han Solo' }
  7. ],
  8. mpaa: {
  9. rating: 'PG-13',
  10. reason: 'sci-fi action violence'
  11. }
  12. });
  13. movie.get('actors').pop();
  14. movie.get('mpaa').rating = 'PG';
  15. console.log(movie.toObject());
  16. /* writes
  17. { name: 'Star Wars',
  18. episode: 7,
  19. actors: List [ Map { "name": "Daisy Ridley", "character": "Rey" }, Map { "name": "Harrison Ford", "character": "Han Solo" } ],
  20. mpaa: Map { "rating": "PG-13", "reason": "sci-fi action violence" } }
  21. */

So let's say you want to modify movie.mpaa.rating. You might think of doing something like this: movie = movie.get('mpaa').set('rating', 'PG'). However, set will always return the calling Map instance, which in this case returns the Map bound to the mpaa key rather than the movie you wanted. We must use the setIn method to update nested properties.

  1. let movie = Immutable.fromJS({
  2. name: 'Star Wars',
  3. episode: 7,
  4. actors: [
  5. { name: 'Daisy Ridley', character: 'Rey'},
  6. { name: 'Harrison Ford', character: 'Han Solo' }
  7. ],
  8. mpaa: {
  9. rating: 'PG-13',
  10. reason: 'sci-fi action violence'
  11. }
  12. });
  13. movie = movie
  14. .update('actors', actors => actors.pop())
  15. .setIn(['mpaa', 'rating'], 'PG');
  16. console.log(movie.toObject());
  17. /* writes
  18. { name: 'Star Wars',
  19. episode: 7,
  20. actors: List [ Map { "name": "Daisy Ridley", "character": "Rey" } ],
  21. mpaa: Map { "rating": "PG", "reason": "sci-fi action violence" } }
  22. */

We also added a call to Map.update which, unlike set, accepts a function as the second argument instead of a value. This function accepts the existing value at that key and must return the new value of that key.

原文: https://angular-2-training-book.rangle.io/handout/immutable/immutable-js/nested-objects/