如何在不覆盖顶级键的情况下分配新的键值对?

时间:2016-09-05 16:53:30

标签: reactjs redux lodash

如何在不重写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

1 个答案:

答案 0 :(得分:1)

请使用mapValues功能代替map功能。更新了以下代码。

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