蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-lists-and-keys.py
explore-lists-and-keys.py262 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/react-lists-and-keys-lab/explore-lists-and-keys.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-lists-and-keys.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3178.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习