首页 > 解决方案 > 为什么在 React 中使用 .map() 时需要扩展运算符,但在纯 JavaScript 中不需要?

问题描述

在 React 应用程序中,我将这个对象数组传递给组件:

const flashcards = [
    {
        "back": "bbb1",
        "front": "fff1",
        "id": 21
    },
    {
        "back": "bbb2",
        "front": "fff2",
        "id": 22
    },
    {
        "back": "bbb3",
        "front": "fff3",
        "id": 20
    }
];

在组件中,当我映射数组时,为什么我需要一个扩展运算符才能将数组中的单个项目发送到下一个较低的组件(抽认卡),例如:

render() {
    return (
        <div className="app">
            <div>
                {this.props.flashcards.map(flashcard =>
                    <Flashcard {...flashcard} key={flashcard.id} />
                    )}
            </div>
        </div>
    );
}

这似乎是多余的,因为当我在同一个数组上使用纯 JavaScript 中的 map 时,我不需要扩展运算符,例如:

flashcards.map(flashcard => console.log(flashcard.front));

标签: javascriptreactjs

解决方案


{...flashcard}- 这基本上将对象中的属性传播到组件将接收的对象flashcard上。propsFlashcard

如果您不想将flashcard对象的所有属性作为道具传递给Flashcard组件,则不需要这样做。

想想这个

<Flashcard {...flashcard} key={flashcard.id} />

作为写这个的更短的方式:

<Flashcard
   key={flashcard.id}
   back={flashcard.back}
   front={flashcard.front}
   id={flashcard.id}
/>

推荐阅读