[英]add item into specific list array redux
I know there is a lot of similar threads but I didn't find a solution there.我知道有很多类似的线程,但我没有找到解决方案。
Okay so I have a state which looks:好的,所以我有一个 state,它看起来:
[
{
id: 1,
title: 'todo',
items: [
{
itemID: 1,
itemText: 'finish this project'
},
{
itemID: 2,
itemText: 'take trash out'
},
{
itemID: 3,
itemText: 'sleep'
},
]
},
{
id: 2,
title: 'doing now',
items: [
{
itemID: 1,
itemText: 'add redux'
},
{
itemID: 2,
itemText: 'fixing bugs'
},
]
},
{
id: 3,
title: 'done',
items: [
{
itemID: 1,
itemText: 'add components'
},
{
itemID: 2,
itemText: 'add material ui'
},
]
}
] ]
and I have a redux reducer that should add an item into specific list, I have id of that list, and itemText which I should add.我有一个 redux 减速器,它应该将一个项目添加到特定列表中,我有该列表的 ID,以及我应该添加的 itemText。 I managed somehow to make it kinda work, it is adding item into specifin array but problem is that also creates new blank list.我设法让它有点工作,它将项目添加到特定数组中,但问题是这也会创建新的空白列表。 Here is how reducer looks:这是减速器的外观:
case "ADD_ITEM":
return [
state.map((list)=>(
(list.id === action.payload.id) ? list.items.push({
itemID: 89,
itemText: action.payload.description
}) : list
))
]
Any idea how to add an item to specific list items without creating a new list?知道如何在不创建新列表的情况下将项目添加到特定列表项吗?
Map and return the lists ( state
), and use spread syntax to update the items
: Map 并返回列表( state
),并使用扩展语法更新items
:
case "ADD_ITEM":
return state.map(list =>
list.id === action.payload.id ? {
...list,
items: [
...list.items,
{
itemID: 89,
itemText: action.payload.description
}
]
} : list
)
Try this:尝试这个:
case "ADD_ITEM":
state.forEach((list, index)=>(
if (list.id === action.payload.id){
state[index].items.push({
itemID: 89,
itemText: action.payload.description
}
})
))
Note that this is pseudocode, but it should still work.请注意,这是伪代码,但它仍然可以工作。
Your example was not working because you were return
ing a new array, which had (about) the same structure as state
, except with the added element.您的示例不起作用,因为您正在return
一个新数组,该数组具有(大约)与state
相同的结构,除了添加的元素。 To add it, simply add it directly to state
without using map
+ return
, thereby not creating a new array.要添加它,只需将其直接添加到state
而不使用map
+ return
,因此不会创建新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.