【问题标题】:Merging values from an item in an array and an object in redux合并数组中的项目和redux中的对象的值
【发布时间】:2016-07-29 13:24:36
【问题描述】:

所以我一直在使用 redux 和 reactjs,虽然问题不相关:

我有这个收藏

const items = [
  {id: 0, name: 'one'},
  {id: 1, name: 'two'},
  {id: 2, name: 'three'}
]

const itemsWithTheFlag = [
  {id: 0, flag: false},
  {id: 1, flag: true},
  {id: 2, flag: false},
]

那么我的初始状态是:

{
  items: items
}

现在我想知道如何在 items 数组中执行查找和更新,

我的一个功能是模拟async 请求并从itemsWithTheFlag 接收项目

export function fetch(id) {
  const desiredItem = find(itemsWithTheFlag, (item) => (item.id === id))
  return (dispatch, getState) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        dispatch(receiveItem(desiredItem))
        resolve()
      }, 100)
    })
  }
}

现在我需要帮助更新状态,更新后的 merged 值,我收到来自 fetch 和初始状态 items

[RECEIVE_ITEM]: (state, action) => {
  return Object.assign({}, state, {
    // how ??
  })
}

我当然想保持不变性,使用 lodash 也可以

【问题讨论】:

  • itemsWithTheFlag 有重复的 ID。这是故意的还是只是一个错字?
  • @YuryTarabanko 是的,这是一个错字

标签: javascript reactjs redux lodash array-merge


【解决方案1】:

您需要重新创建整个数组并使用相应的 id 修补项目。

return Object.assign({}, state, {
    items: state.items.map(
       item => (
         item.id === action.desiredItem.id
         ? Object.assign({}, item, desiredItem)
         : item)
    )
  })

【讨论】:

    【解决方案2】:

    您需要返回一个新数组,只换出该项目。这种方式的好处是不会遍历所有state.items,这在大型数组上性能更高(但本例中的解决方案确实使用了lodash)

    const index = _.findIndex(state.items, { id: action.newItem.id });
    return {
      ...state,
      items: [
        ...state.items.slice(0, index),
        { ...state.items[index], ...action.newItem },
        ...state.items.slice(index + 1)
      ]
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2011-04-04
      • 2017-01-17
      • 1970-01-01
      相关资源
      最近更新 更多