How to update element inside List with ImmutableJS?

后端 未结 7 1165
面向向阳花
面向向阳花 2020-12-04 09:02

Here is what official docs said

updateIn(keyPath: Array, updater: (value: any) => any): List
updateIn(keyPath: Array, notSe         


        
7条回答
  •  臣服心动
    2020-12-04 09:21

    I really like this approach from the thomastuts website:

    const book = fromJS({
      title: 'Harry Potter & The Goblet of Fire',
      isbn: '0439139600',
      series: 'Harry Potter',
      author: {
        firstName: 'J.K.',
        lastName: 'Rowling'
      },
      genres: [
        'Crime',
        'Fiction',
        'Adventure',
      ],
      storeListings: [
        {storeId: 'amazon', price: 7.95},
        {storeId: 'barnesnoble', price: 7.95},
        {storeId: 'biblio', price: 4.99},
        {storeId: 'bookdepository', price: 11.88},
      ]
    });
    
    const indexOfListingToUpdate = book.get('storeListings').findIndex(listing => {
      return listing.get('storeId') === 'amazon';
    });
    
    const updatedBookState = book.setIn(['storeListings', indexOfListingToUpdate, 'price'], 6.80);
    
    return state.set('book', updatedBookState);
    

提交回复
热议问题