Replace array item with another one without mutating state

后端 未结 3 856
死守一世寂寞
死守一世寂寞 2021-01-01 18:52

This is how example of my state looks:

const INITIAL_STATE = {
 contents: [ {}, {}, {}, etc.. ],
 meta: {}
}

I need to be able and somehow

3条回答
  •  粉色の甜心
    2021-01-01 19:39

    Splice mutate the array you need to use Slice . And you also need to concat the sliced piece .

    return Object.assign({}, state,  {
             contents:
              state.contents.slice(0,action.meta.index)
              .concat([{
                content_type: 7,
                content_body: {
                  album_artwork_url: action.payload.data.album.images[1].url,
                  preview_url: action.payload.data.preview_url,
                  title: action.payload.data.name,
                  subtitle: action.payload.data.artists[0].name,
                  spotify_link: action.payload.data.external_urls.spotify
                }
              }])
              .concat(state.contents.slice(action.meta.index + 1))
      }
    

提交回复
热议问题