【问题标题】:How to assign new key value pair without overwriting top level keys?如何在不覆盖顶级键的情况下分配新的键值对?
【发布时间】:2016-09-05 16:53:29
【问题描述】:

如何在不覆盖 Redux reducer 中顶级键的情况下向嵌套对象添加键/值对?

注释之前的状态:

notes: {
  -KQpqwDTyLOzd-8UXi-z: {
    created: 1473035305252,
    text: 'stuff',
  }
  -KQqe4xiwV4-5WIs2Gpg: {
    created: 1473017044898,
    text: 'more stuff',
  }
}

注释之后的状态:

notes: {
  0: {
    created: 1473035305252,
    text: 'stuff',
    new: 'new value',
  }
  1: {
    created: 1473017044898,
    text: 'more stuff',
  }
}

这是产生上述结果的减速器:

import _ from 'lodash'

const notes = (state = [], action) => {
  switch (action.type) {
    case 'FETCH_NOTES':
      return action.payload;
    case 'CLEAR_NOTES':
      return state = [];
    case 'UPDATE_NOTE':
      console.log(state)
      return _.map(state, (note, index) => {
        if (index === action.id) {
          return _.assign({}, note, {
            new: action.new
          })
        }
        return note
      })
    default:
      return state
  }
}
export default notes

【问题讨论】:

    标签: reactjs redux lodash


    【解决方案1】:

    请使用mapValues 函数而不是map 函数。下面更新了代码。

    return _.mapValues(state, (note, index) => {
        if (index === action.id) {
          return _.assign({}, note, {
            new: action.new
          })
        }
        return note
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多