【发布时间】:2021-09-24 16:09:53
【问题描述】:
我了解以下代码将一个新对象添加到对象数组中,但在特定语法上很模糊:setProductList([array, obj])
据我所见,setProductList 函数接受一个对象。该对象由一个数组和一个对象组成。那么它是如何将对象添加到数组中的呢?这是内置在 JS 还是 React 中的?
// array of products
const Products = [
{
item: "basketball",
price: 3,
description: "basketball desc",
},
{
item: "football",
price: 5,
description: "football desc",
},
];
// setting state
const [productList, setProductList] = useState(Products);
// handling click
const handleClick = () => {
// Don't quite understand the syntax of below block
setProductList([
...productList, // spread creates a copy of the array
{
item: "baseball",
price: 4,
description: "baseball desc",
},
]);
};
【问题讨论】:
-
That object consists of an array and an object不,它由对象数组组成
标签: javascript reactjs setstate