[英]ReactJS - What is the best way to push data in an array within an array?
[英]What is the best way to add data array in an array?
我有一个 state object ,其中有一个类别数组。 在这个对象数组中,object 的一个键(“列表”)被分配了一个数组。 我需要做的是
例子
const initialState = {
category: [
{
name: "new",
color: "#5236C1",
list: [
{
title: "name title",
about: "about",
imgLink: 'https://www.google.com/s2/favicons?domain=https://mail.yandex.ru/',
url: 'https://www.yandex.ru'
},
// there should be a new object
]
},
试图这样做
const addBM = (state, payload) => {
console.log(payload)
const {url, title, about, cat} = payload
let selectCatArr = state.category.filter((item) => item.name == cat)
return {
...state,
category: [...state.category, {list: [title, url, about ]}]
}
}
应该有一个新的 object
我修改了 addBM function 并添加了一些解释代码的注释。
const addBM = (state, payload) => {
console.log(payload)
const {url, title, about, cat} = payload
// use map method instead of filter
const modifiedCategory = state.category.map(categoryItem => {
// only modify the category item if it's name matches the cat argument
// otherwise return the original category item
if (categoryItem.name == cat) {
// create a copy of the category item object
let modifiedCategoryItem = {
...categoryItem,
// modify the list array of this object by
// creating a copy of the array and
// adding a new object with (url, title and about arguments) in this array
list: [...categoryItem.list, {url, title, about}]
};
return modifiedCategoryItem;
} else {
return categoryItem;
}
});
return {
...state,
category: modifiedCategory
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.