javascript - 为什么在 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));
解决方案
{...flashcard}
- 这基本上将对象中的属性传播到组件将接收的对象flashcard
上。props
Flashcard
如果您不想将flashcard
对象的所有属性作为道具传递给Flashcard
组件,则不需要这样做。
想想这个
<Flashcard {...flashcard} key={flashcard.id} />
作为写这个的更短的方式:
<Flashcard
key={flashcard.id}
back={flashcard.back}
front={flashcard.front}
id={flashcard.id}
/>
推荐阅读
- r - 用于 Shiny Dashboard 的 R 编程词云
- c# - C# Unity 序列化 Vector3 类型
- airflow - 在谷歌作曲家中删除 DAG - Airflow UI
- internet-explorer - 带有 IE 的 JAWS 键盘快捷键
- c# - 在 .NET 4.7.2 的 WebForms 中连接 Simple Injector
- php - 我应该如何使用 fpdf 设置 pdf 的下载名称?
- java - ClassNotFoundException : com.mysql.jdbc.Driver 但它在类路径中
- python - 使用脚本自动记事本++编辑csv文件
- css - 如何让元素与它旁边的元素对齐?
- sql-server - 从 mssql 表插入触发器触发 nodejs 函数