用另一项替换数组项而不改变状态 [英] Replace array item with another one without mutating state

查看:96
本文介绍了用另一项替换数组项而不改变状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的状态示例的样子:

This is how example of my state looks:

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

我需要能够以某种方式替换目录数组中的一项,知道它的索引,我已经尝试过:

I need to be able and somehow replace an item inside contents array knowing its index, I have tried:

      return {
        ...state,
        contents: [
          ...state.contents[action.meta.index],
          {
            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
            }
          }
        ]
      }

其中action.meta.index是我要用另一个内容对象替换的数组项的索引,但是我相信这只是将整个数组替换为我要传递的这个对象.我还考虑过使用.splice(),但是那样只会改变数组?

where action.meta.index is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice() but that would just mutate the array?

推荐答案

Splice更改您需要使用Slice的数组.并且您还需要concat切片.

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))
  }

这篇关于用另一项替换数组项而不改变状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆