[英]How to update react redux state Object of id - key value pair
I have a variable in my redux state that seems to be an Object of key as id and value as content,我的 redux state 中有一个变量,这似乎是一个 Object 的键作为 id 和值作为内容,
, as you can see this state variable, let's call it
capacity
, is not an array or list but a plain object, and I want to increase one of the item property availableCapacity
to be the value in my action payload by id, so here is what I can do ,如您所见,这个 state 变量,我们称之为
capacity
,不是数组或列表,而是一个普通的 object,我想增加一个 item 属性availableCapacity
,使其成为我的动作有效负载中的值,所以这里是我可以做什么
const updatedCapacity = {
...state.capacity[id],
availableCapacity: state[id].availableCapacity + 1
};
and my updatedCapacity
will be look like我的
updatedCapacity
看起来像
{
active: true
avaialbleCapacity: 31
capacity: "2febf..."
totalCapacityAvailable: 30
}
but then how could I find the element in my state by id then replace it with my modified updatedCapacity
?但是我怎么能通过 id 在我的 state 中找到元素,然后用我修改后的
updatedCapacity
替换它? I have tried below but instead, it added a new entry in my state.capacity in first example, and in 2nd example it added a new entry of key value "id", not my exact id of "2febfxxxx"...我在下面尝试过,但是相反,它在第一个示例中在我的 state.capacity 中添加了一个新条目,在第二个示例中,它添加了一个新的键值“id”条目,而不是我的“2febfxxxx”的确切 id...
case UPDATE_CAPACITY:
return {
...state.capacity,
updatedCapacity
}
or
case UPDATE_CAPACITY:
return {
...state.capacity,
id: { updatedCapacity }
}
Shallowly copy all state for the objects you are updating.为您正在更新的对象浅复制所有 state。 You can use the
id
as a dynamic key.您可以将
id
用作动态键。
case UPDATE_CAPACITY:
return {
...state, // <-- copy current state
[id]: {
...state[id], // <-- copy current element
availableCapacity: state[id].availableCapacity + 1 // <-- increment capacity
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.