gpt4 book ai didi

reactjs - 通过map函数了解rest和spread参数的用法

转载 作者:行者123 更新时间:2023-12-03 08:52:51 26 4
gpt4 key购买 nike

我想了解如何在js中正确使用...运算符,尤其是与js的map函数一起使用。

假设我们有以下数据:

const SHOP_DATA = [
{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25
}]
}
]

现在我想将值作为 props 发送到另一个组件:

SHOP_DATA.map(({ id, ...otherProps }) => (
<CollectionPreview key={id} {...otherProps} />

如果我理解正确的话,第一个 ... 是一个休息运算符,这意味着我们正在将值汇集到一个新数组中。第二个...是一个扩展运算符,这意味着我们正在从数组中扩展这些值

然后我们需要在 CollectionPreview 中再次使用 ... 运算符将它们展开。

const CollectionPreview = ({ id, ...otherProps }) => {

我不明白数据流,为什么我们刚才所做的相当于做:

SHOP_DATA.map(({ id, title , items }) => (
<CollectionPreview key={id} title = {title} items = {items} />

最佳答案

SHOP_DATA.map(({ id, ...otherProps })

在这里,您正在解构每个 SHOP_DATA的对象属性,并使用对象的剩余运算符来初始化名为 otherProps 的对象所有对象属性减去之前指定的属性(在本例中为“id ”):

otherProps = {
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25,
},
],
};

<CollectionPreview key={id} {...otherProps} />

这里使用的是 JSX 展开运算符,这与对象展开运算符有点不同,它将对象的所有属性展开到通过属性名称命名的组件 props,结果:

<CollectionPreview key={id} title="Hats" routeName="hats" items={[{ id: 1, name: "Brown Brim", etc.. }]} />

const CollectionPreview = ({ id, ...otherProps }) => {

在组件声明中,您不必使用对象休息运算符,如果您知道 Prop 名称,则可以像这样单独使用它们:

const CollectionPreview = ({ id, title, routeName, items }) => {

关于reactjs - 通过map函数了解rest和spread参数的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57856788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com