Skip to content

列表渲染

一句话解释

列表渲染平均值 transforming 数组的 数据到 数组的 JSX 元素 using .映射() 方法.

用大白话说

到渲染列表的 项 in React, 你 take 你的数据数组 and call .map() to transform each data item into a JSX element. React renders each element in the resulting array.

Every item in a list must have a unique 键 prop. Keys help React identify which items changed, were added, or were removed, enabling efficient reconciliation. Use a stable unique ID from your data as the key — avoid using array indices as keys if the list can be reordered or items can be inserted/removed, because that causes subtle bugs.

映射() returns a new array, which React renders as a fragment of siblings. You can also use 筛选() before 映射() to render only matching items.

示例

jsx
const fruits = [
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Cherry" },
];

function FruitList() {
  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}

映射 transforms 每个 fruit 对象到 <li>. 键 prop uses 唯一 id 所以 React 能 track 项跨越 re-渲染.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表