在不改变状态的情况下用另一个替换数组项

Replace array item with another one without mutating state

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

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

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

      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() 但这只会改变数组?

Splice 改变你需要使用的数组 Slice 。而且你还需要 concat 切片。

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

只是以@sapy 的正确答案为基础。我想向您展示另一个示例,说明如何在不改变状态的情况下更改 Redux 中数组内对象的 属性。

我所在的州有一个 orders 数组。每个 order 都是一个包含许多属性和值的对象。然而,我只想更改 note 属性。所以像这样的东西

let orders = [order1_Obj, order2_obj, order3_obj, order4_obj];

例如 order3_obj = {note: '', total: 50.50, items: 4, deliverDate: '07/26/2016'};

所以在我的 Reducer 中,我有以下代码:

return Object.assign({}, state,
{
  orders: 
    state.orders.slice(0, action.index)
    .concat([{
      ...state.orders[action.index],
      notes: action.notes 
    }])
    .concat(state.orders.slice(action.index + 1))
   })

所以基本上,您正在执行以下操作:

1) 切出order3_obj之前的数组,所以[order1_Obj, order2_obj]

2) 使用三点 ... 扩展运算符和您要更改的特定 属性 连接(即添加)已编辑的 order3_obj(即 note)

3) 在订单数组的其余部分使用 .concat.slice 在末尾 .concat(state.orders.slice(action.index + 1)) 连接,这是 order3_obj 之后的所有内容(在本例中为 order4_obj是唯一剩下的)。

请注意,Array.prototype.map() (docs) 不会 改变原始数组,因此它提供了另一个选项:

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

 // Assuming this action object design
 {
   type: MY_ACTION,
   data: {
     // new content to replace
   },
   meta: {
     index: /* the array index in state */,
   }
 }

 function myReducer(state = INITIAL_STATE, action) {
   switch (action.type) {
     case MY_ACTION: 
       return {
         ...state,
         // optional 2nd arg in callback is the array index
         contents: state.contents.map((content, index) => {
           if (index === action.meta.index) {
             return action.data
           }

           return content
         })
       }
   }
 }