学习库ReactLists and Keys

Lists and Keys

Render collections predictably and give React stable identity for every item.

更新于 适用于 React 19.2

Render collections by transforming data into elements. A key tells React which item corresponds to which previous item across inserts, removals, and reordering.

Map data into elements

LessonList.tsx
function LessonList({ lessons }) {
  return <ol>{lessons.map((lesson) => (
    <li key={lesson.id}><a href={lesson.href}>{lesson.title}</a></li>
  ))}</ol>;
}

Keys must be unique among siblings and stable for the lifetime of the item. Use an ID from the data.

Preserve identity

Do not generate keys while rendering and avoid array indexes when items can move or be deleted. Incorrect keys can preserve state on the wrong row.

CourseRows.tsx
const visible = courses.filter((course) => course.available);
return visible.map((course) => <CourseRow key={course.slug} course={course} />);

Keep this

Transform collections declaratively and choose keys from stable data identity, not rendering position.

学习位置已保存在此设备上。