嵌套对象

Immutable.Map以浅的方式包装对象,这意味着如果你有一个对象的属性绑定到可变类型,那么这些属性可以被改变。

  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. */

要避免此问题,请改用Immutable.fromJS

  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. */

所以,当你想修改movie.mpaa.rating。 你可能会想这样做:movie = movie.get('mpaa').set('rating','PG')。 然而,set将总是返回调用Map实例,在这种情况下返回映射绑定到mpaa键,而不是你想要的电影。 我们必须使用setIn方法来更新嵌套属性。

  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. */

我们还添加了一个对Map.update的调用,与set不同,它接受一个函数作为第二个参数,而不是一个值。 此函数接受该键处的现有值,并且必须返回该键的新值。