本文介绍了如何分配新的键值对而不覆盖顶级键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在嵌套对象中添加键/值对而不覆盖Redux reducer中的顶级键?
How do I add a key/value pair to a nested object without overwriting the top level keys in my 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',
}
}
这是我的减速器,可产生以上结果:
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
推荐答案
请使用 mapValues 函数代替 map 功能.下面更新了代码.
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
})
这篇关于如何分配新的键值对而不覆盖顶级键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!