列表渲染
渲染数组的 数据使用映射, importance 的键, and 常见列表模式.
你将学到
- Using .映射() 到 transform 数组到 JSX 元素
- 为什么键 是必要 and 如何 选择它们
- 筛选 and 排序列表之前渲染
- 常见 pitfalls 使用索引-based 键
概念讲解
Rendering Lists with map
In React, you render lists of data using the JavaScript 数组.映射() method. You call map on your data array and return a JSX element for each item. React then renders each element in order. This is pure JavaScript — there is no special v-for or *ngFor directive. The map call goes inside JSX curly braces: {项.映射(项 => <li>{项.name}</li>)}.
The Importance of Keys
Every element in a list must have a unique key prop. Keys help React identify which items have changed, been added, or been removed, allowing it to efficiently update the DOM. Without keys, React may unnecessarily re-render or incorrectly reuse DOM nodes, causing subtle bugs. Keys must be unique among siblings — they do not need to be globally unique. The best key is a stable, unique identifier from your data, like a database ID.
Why Not Use Array Index as Key?
Using the array index as a key (键={索引}) is tempting but problematic if the list can be reordered, filtered, or items can be inserted at the beginning. When the order changes, the indices stay the same but the data behind them changes, so React may reuse the wrong DOM nodes. This can cause state to get attached to the wrong item or animations to break. Use index keys only for static lists that never change order.
Filtering and Sorting
You can chain array methods before mapping: 项.筛选(...).排序(...).映射(...). However, be mindful of performance — filtering and sorting on every render can be expensive for large lists. Consider memoizing the result with useMemo (which you will learn about later) if the list is large and the source data does not change often.
The key Prop in Depth
Keys are React's identity tracker for list items. When a key changes, React treats the element as new and creates a new DOM node. When a key stays the same across renders, React reuses the existing DOM node and updates only the changed attributes. This is why stable, unique keys from your data (like database IDs) are ideal — they let React minimize DOM operations.
示例代码
import { useState } from "react";
function ProductList({ products }) {
const [filter, setFilter] = useState("");
// Filter then map — chain array methods for derived data.
const visibleProducts = products
.filter(p => p.name.toLowerCase().includes(filter.toLowerCase()))
.map(product => (
<li key={product.id} className="product-item">
<h3>{product.name}</h3>
<p>Price: ${product.price}</p>
<span className={product.inStock ? "in-stock" : "out-of-stock"}>
{product.inStock ? "In Stock" : "Sold Out"}
</span>
</li>
));
return (
<div>
<input placeholder="Search products..."
value={filter} onChange={e => setFilter(e.target.value)} />
<ul>{visibleProducts}</ul>
</div>
);
}
每个列表项 有 stable 键从 product.id (不数组索引). 筛选 narrows 列表, and 映射 transforms 每个 product 到 JSX.
动手试一试
- JSON Formatter
列表数据通常 comes as JSON 数组 — 格式 and inspect 它们.
- JSON 到 CSV
导出你的列表数据到 CSV for spreadsheets or reports.
常见错误
错误写法
Using 数组索引 as 键 for 动态列表
正确做法
Use stable 唯一 ID 从你的数据 (e.g., product.id, 用户.id). 索引键 cause bugs 当项 是 reordered, inserted, or 删除因为 React reuses 错误 DOM 节点.
错误写法
Forgetting 键 prop 完全
正确做法
React 将 warn in console and 可能渲染不正确地. 总是 provide 唯一键 prop 到每个元素 in mapped 列表. 键必须是 唯一其中 siblings.
练习 列表渲染
8 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。