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

Understand the usage of rest and spread parameters with the map function

我想了解如何正确使用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} />

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

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

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

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

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

为此,您还需要熟悉解构。

如果你有对象:

const human = { name: 'John', age: 20, sex: 'Male'}

你可以把物品的道具拿出来像:

const {name, age, sex} = human

现在,name -> 'John, age -> 20, sex -> 'Male'

但如果你这样做

const {name, ...rest} = human
name -> 'John'
rest -> { age: 20, sex: 'Male'}

现在让我们转到您的代码:

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

在这里,您正在映射数组并动态解构对象。

id -> 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} />

会变成

 <CollectionPreview key={id} title={title} routerName={routeName} 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 展开运算符,这与对象展开运算符有点不同,它将对象的所有属性展开到组件属性中,命名它们属性名称,结果:

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

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

在组件声明中,您不会被迫使用 object rest operator,如果您知道您的 props 名称,您可以像这样单独使用它们:

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