蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

React 列表 & Keys

核对 map() 列表渲染、唯一稳定 Key 与数组索引 Key 在头部插入时的真实 DOM 状态对比、提取组件时的 Key 放置位置,以及兄弟唯一性与不可经 props.key 读取规则。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

使用 map() 渲染列表与 Key 的作用

React 使用标准 JavaScript `Array.prototype.map()` 将数据数组映射为 React 元素数组,再放入 `<ul>{listItems}</ul>` 等容器中渲染。当列表项未提供 `key` 时,React 开发模式会发出 `a key should be provided for list items` 警告;将逻辑重构为接收 `props.numbers` 的 `NumberList` 组件并为每项指定 `key={number.toString()}` 后即可消除告警。本站离线 Chromium 实测未加 `key` 触发 5 条告警,补充 `key` 后告警归零并准确渲染 `["1", "2", "3", "4", "5"]`。

Key 帮助 React 协调器识别列表中哪些项被新增、移动或删除,从而精准复用对应 DOM 节点与组件内部状态。最佳选择是数据条目自带的稳定唯一标识(如数据库主键 `todo.id`);仅在列表绝对静态、不会重排或删改且无唯一 ID 时,才退而求其次使用索引 `index`。若可重排或头部插入的列表误用 `index` 作 `key`,不仅拖慢差异复用,更会引发严重的状态错位。本站实测向带输入框的 `[Apple, Banana]` 头部插入 `Cherry`(此前在 `Apple` 输入框键入 `note-A`):使用 `key={item.id}` 时原 `Apple` DOM 节点引用保持同一对象,`note-A` 准确跟随 `Apple`;改用 `key={index}` 后索引 `0` 被复用,导致 `note-A` 错误附着到了新插入的 `Cherry` 行上。

提取列表项组件时的 Key 正确位置

Key 仅在当前数组兄弟节点之间做协调对比时生效。因此,当把单个列表项抽离为 `<ListItem />` 组件时,必须把 `key` 写在 `map()` 内部直接返回的 `<ListItem key={number.toString()} value={number} />` 元素上,而不是写在 `ListItem` 内部返回的 `<li>` 标签上——经验法则是“紧贴 `map()` 调用内部的元素才需要指定 `key`”。本站实测把 `key` 误放在子组件内部 `<li>` 上时仍产生 3 条缺键告警,移至 `<ListItem />` 后告警清零。

兄弟唯一性、props.key 不可读与 JSX 内联 map()

Key 只需在相邻兄弟元素之间保持唯一,不必全局唯一:同一份 `posts` 数组在 `Blog` 组件中分别渲染侧边栏 `<ul>` 与正文区 `<div>` 时,两组列表均可安全复用 `post.id` 作为 `key` 而互不冲突。此外,`key` 是专供 React 协调器读取的内部提示,不会透传进子组件 `props`;如果子组件业务代码需要该 ID,必须显式另传一个自定义属性(如 `id={post.id}`)。本站实测 `Blog` 两组列表告警数为 `0`,而 `Post` 组件内 `props.id` 分别为 `1`/`2`、`props.key` 均为 `undefined`。

除先声明 `listItems` 变量外,JSX 也允许直接在花括号内嵌入 `numbers.map(...)` 表达式。两种写法语义完全等价,选择标准应以代码清晰度为准:表达式简洁时可直接内联,一旦 `map()` 嵌套层级过深或包含复杂条件,就应提取中间变量或拆分为独立子组件。

离线 Chromium 对比唯一 ID Key 与索引 Key 的 DOM 复用及 Key 位置/透传规则

python · 阅读源码
"""Offline Chromium lab for React Ch 18: lists-and-keys."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Lists and Keys Lab</title></head>
<body>
  <div id="map-root"></div>
  <div id="key-id-root"></div>
  <div id="key-idx-root"></div>
  <div id="blog-root"></div>
  <script>
    'use strict';

    const warnings = [];

    function createElement(type, props, ...children) {
      const p = Object.assign({}, props || {});
      const key = p.key !== undefined ? String(p.key) : null;
      delete p.key; // React strips key so components cannot read props.key
      const flat = [];
      for (const ch of children) {
        if (Array.isArray(ch)) {
          const seen = new Set();
          for (const item of ch) {
            if (item && typeof item === 'object') {
              if (item.key === null) {
                warnings.push('Warning: Each child in a list should have a unique "key" prop.');
              } else if (seen.has(item.key)) {
                warnings.push('Warning: Encountered two children with the same key: ' + item.key);
              } else {
                seen.add(item.key);
              }
            }
            flat.push(item);
          }
        } else if (ch !== null && ch !== undefined && typeof ch !== 'boolean') {
          flat.push(ch);
        }
      }
      p.children = flat;
      return { type, key, props: p };
    }

    function renderStatic(vnode) {
      if (typeof vnode === 'string' || typeof vnode === 'number') return document.createTextNode(String(vnode));
      if (typeof vnode.type === 'function') return renderStatic(vnode.type(vnode.props));
      const el = document.createElement(vnode.type);
      vnode.props.children.forEach(c => el.appendChild(renderStatic(c)));
      return el;
    }

    // Keyed list reconciler preserving DOM nodes by key (matching React reconciliation)
    function reconcileList(ul, items, keyFn) {
      const existingByKey = new Map();
      for (const li of Array.from(ul.children)) {
        existingByKey.set(li.dataset.reactKey, li);
      }
      const nextNodes = items.map((item, index) => {
        const k = String(keyFn(item, index));
        let li = existingByKey.get(k);
        if (!li) {
          li = document.createElement('li');
          li.dataset.reactKey = k;
          const span = document.createElement('span');
          const input = document.createElement('input');
          li.appendChild(span);
          li.appendChild(input);
        }
        li.querySelector('span').textContent = item.label;
        return li;
      });
      // Remove obsolete nodes
      const keep = new Set(nextNodes);
      for (const li of Array.from(ul.children)) {
        if (!keep.has(li)) ul.removeChild(li);
      }
      // Insert/reorder while preserving DOM node identity
      nextNodes.forEach((node, idx) => {
        if (ul.children[idx] !== node) {
          ul.insertBefore(node, ul.children[idx] || null);
        }
      });
    }

    window.runLab = function () {
      // Case 1: map() without key vs with key
      warnings.length = 0;
      const numbers = [1, 2, 3, 4, 5];
      const badList = createElement('ul', null, numbers.map(n => createElement('li', null, n)));
      const badWarningsCount = warnings.length;
      warnings.length = 0;
      const goodList = createElement('ul', null, numbers.map(n => createElement('li', { key: n.toString() }, n)));
      const goodWarningsCount = warnings.length;
      const mapRoot = document.getElementById('map-root');
      mapRoot.appendChild(renderStatic(goodList));
      const case1 = {
        rendered_items: Array.from(mapRoot.querySelectorAll('li')).map(li => li.textContent),
        missing_key_warnings: badWarningsCount,
        with_key_warnings: goodWarningsCount
      };

      // Case 2: Stable unique id key vs index key when prepending an item with stateful <input>
      const idUl = document.createElement('ul');
      document.getElementById('key-id-root').appendChild(idUl);
      const idxUl = document.createElement('ul');
      document.getElementById('key-idx-root').appendChild(idxUl);

      const initialItems = [
        { id: 'a', label: 'Apple' },
        { id: 'b', label: 'Banana' }
      ];
      reconcileList(idUl, initialItems, (it) => it.id);
      reconcileList(idxUl, initialItems, (_, i) => i);

      const appleNodeIdBefore = idUl.children[0];
      idUl.children[0].querySelector('input').value = 'note-A';
      idxUl.children[0].querySelector('input').value = 'note-A';

      const prependedItems = [
        { id: 'c', label: 'Cherry' },
        { id: 'a', label: 'Apple' },
        { id: 'b', label: 'Banana' }
      ];
      reconcileList(idUl, prependedItems, (it) => it.id);
      reconcileList(idxUl, prependedItems, (_, i) => i);

      const idSnapshot = Array.from(idUl.children).map(li => ({
        label: li.querySelector('span').textContent,
        inputVal: li.querySelector('input').value
      }));
      const idxSnapshot = Array.from(idxUl.children).map(li => ({
        label: li.querySelector('span').textContent,
        inputVal: li.querySelector('input').value
      }));

      const case2 = {
        id_key_preserves_apple_dom_node: idUl.children[1] === appleNodeIdBefore,
        id_key_state: idSnapshot,
        index_key_state_corrupted: idxSnapshot
      };

      // Case 3: Extracted ListItem component - wrong key inside ListItem vs correct key on <ListItem />
      warnings.length = 0;
      function WrongListItem(props) { return createElement('li', { key: props.value.toString() }, props.value); }
      createElement('ul', null, [1, 2, 3].map(n => createElement(WrongListItem, { value: n })));
      const wrongPlacementWarnings = warnings.length;

      warnings.length = 0;
      function CorrectListItem(props) { return createElement('li', null, props.value); }
      const correctTree = createElement('ul', null, [1, 2, 3].map(n => createElement(CorrectListItem, { key: n.toString(), value: n })));
      const correctPlacementWarnings = warnings.length;

      const case3 = {
        wrong_placement_warnings: wrongPlacementWarnings,
        correct_placement_warnings: correctPlacementWarnings,
        correct_items_count: correctTree.props.children.length
      };

      // Case 4: Sibling-only uniqueness (Blog sidebar + content reuse post.id) & props.key undefined
      warnings.length = 0;
      const propObservations = [];
      function Post(props) {
        propObservations.push({ id: props.id, keyInProps: props.key === undefined ? 'undefined' : props.key });
        return createElement('div', null, createElement('h3', null, props.title), createElement('p', null, props.content));
      }
      const posts = [
        { id: 1, title: 'Hello World', content: 'Welcome to learning React!' },
        { id: 2, title: 'Installation', content: 'You can install React from npm.' }
      ];
      function Blog(props) {
        const sidebar = createElement('ul', { className: 'sidebar' },
          props.posts.map(post => createElement('li', { key: post.id }, post.title))
        );
        const content = createElement('div', { className: 'content' },
          props.posts.map(post => createElement(Post, { key: post.id, id: post.id, title: post.title, content: post.content }))
        );
        return createElement('div', null, sidebar, createElement('hr', null), content);
      }
      const blogRoot = document.getElementById('blog-root');
      blogRoot.appendChild(renderStatic(createElement(Blog, { posts })));
      const case4 = {
        blog_warnings: warnings.length,
        sidebar_titles: Array.from(blogRoot.querySelectorAll('li')).map(n => n.textContent),
        content_headings: Array.from(blogRoot.querySelectorAll('h3')).map(n => n.textContent),
        post_prop_observations: propObservations
      };

      return { case1, case2, case3, case4 };
    };
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runLab()")
        browser.close()

    expected = {
        "map_list_and_missing_key_warning": {
            "rendered_items": ["1", "2", "3", "4", "5"],
            "missing_key_warnings": 5,
            "with_key_warnings": 0,
        },
        "unique_id_key_vs_index_key_dom_preservation": {
            "id_key_preserves_apple_dom_node": True,
            "id_key_state": [
                {"label": "Cherry", "inputVal": ""},
                {"label": "Apple", "inputVal": "note-A"},
                {"label": "Banana", "inputVal": ""},
            ],
            "index_key_state_corrupted": [
                {"label": "Cherry", "inputVal": "note-A"},
                {"label": "Apple", "inputVal": ""},
                {"label": "Banana", "inputVal": ""},
            ],
        },
        "key_placement_in_extracted_component": {
            "wrong_placement_warnings": 3,
            "correct_placement_warnings": 0,
            "correct_items_count": 3,
        },
        "sibling_uniqueness_and_key_not_in_props": {
            "blog_warnings": 0,
            "sidebar_titles": ["Hello World", "Installation"],
            "content_headings": ["Hello World", "Installation"],
            "post_prop_observations": [
                {"id": 1, "keyInProps": "undefined"},
                {"id": 2, "keyInProps": "undefined"},
            ],
        },
    }
    actuals = {
        "map_list_and_missing_key_warning": out["case1"],
        "unique_id_key_vs_index_key_dom_preservation": out["case2"],
        "key_placement_in_extracted_component": out["case3"],
        "sibling_uniqueness_and_key_not_in_props": out["case4"],
    }
    cases = [
        {"name": name, "expected": expected[name], "actual": actuals[name], "passed": actuals[name] == expected[name]}
        for name in expected
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对缺 key 警告与消除、头部插入列表时 id key 保留 Apple 原 DOM 节点与输入框值而 index key 错位到 Cherry、ListItem 正确放 key、Blog 复用兄弟 key 及 props.key 为 undefined。
离线 Chromium 对比唯一 ID Key 与索引 Key 的 DOM 复用及 Key 位置/透传规则

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:80b885b8cff1cd0bfd9752b14704bba83bafc593f264ba98273de868f26f93e7

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载React 列表 & Keys实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:77402bc7246c37a05d476b1df417204272e47d9cce840596372b41f004eb8947

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么向带表单输入的列表头部插入新项时,`key={index}` 会导致输入框内容错位到错误条目上?为什么组件内部无法读取 `props.key`?

展开参考解答

使用 `index` 作 `key` 时,头部插入使新项占据索引 `0`,React 误认为索引 `0` 对应的原 DOM 节点仍属同一条目而就地复用其 `<input>` 状态,导致旧输入黏附到新项上;`key` 仅供 React 协调器识别节点身份,框架在创建元素时会将其从 `props` 中剥离,需使用时应显式传递 `id` 等属性。

规范与官方依据