How to assign new key value pair without overwriti

2019-09-13 10:10发布

How do I add a key/value pair to a nested object without overwriting the top level keys in my Redux reducer?

notes state before:

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

notes state after:

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

here is my reducer that is producing the above results:

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条回答
够拽才男人
2楼-- · 2019-09-13 10:35

Please use mapValues function instead of map function. Updated code below.

return _.mapValues(state, (note, index) => {
    if (index === action.id) {
      return _.assign({}, note, {
        new: action.new
      })
    }
    return note
  })
查看更多
登录 后发表回答