可能的重复:
- redux - how to store and update a key/value pair
- How to assign new key value pair without overwriting top level keys?
以上可能的重复项不能满足我的需要。
下面是我用来存储为对象数组的redux reducer 代码:
case 'ADD_ITEM':
return {...state, elements:[...state.elements, action.appElements]}
其中 action.appElements
包含:
{id: '9aq05d', width: '100',height: '225'}
存储的对象数组将如下所示:
elements: {
0: {
id: 9aq05d,
width: '100',
height: '225',
}
1: {
id: 8lk65f,
width: '200',
height: '787',
}
}
但我需要将值存储为键值对,如下所示:
我需要id作为 key 。
elements: {
9aq05d: {
id: 9aq05d,
width: '100',
height: '225',
}
8lk65f: {
id: 8lk65f,
width: '200',
height: '787',
}
}
如何在 redux store 中存储这种键值对..?
提前致谢..
最佳答案
使用对象展开而不是数组展开。
case 'ADD_ITEM':
return {
...state,
elements: {
...state.elements,
[action.appElements.id]: action.appElements
}
}
但请记住,对象中键的顺序是无法保证的。
关于reactjs - 如何在 redux 中将状态值存储为键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45541370/