Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【2022.9.5】React当中的key #70

Open
lkzwc opened this issue Sep 5, 2022 · 0 comments
Open

【2022.9.5】React当中的key #70

lkzwc opened this issue Sep 5, 2022 · 0 comments
Labels

Comments

@lkzwc
Copy link
Owner

lkzwc commented Sep 5, 2022

key存在的意义

当界面的UI发生变化的时候,react会成成一个mutation,而react在比对的过程中不能准确的找到该节点是原来的还是需要直接重新生成的,于是就诞生了key

react 使用key 匹配原来树上的子元素以及最新树上的子元素

key的错误用法

function ListItem(props) {
  const value = props.value;
  return (
    // 错误!你不需要在这里指定 key:
    <li key={value.toString()}>
      {value}
    </li>
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // 错误!元素的 key 应该在这里指定:
    <ListItem value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

// 正确的用法

function ListItem(props) {
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // 正确!key 应该在数组的上下文中被指定
    <ListItem key={number.toString()}      value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

一个好的经验是在map方法中的元素需要设置key
也可以使用元素在数组中的下标作为 key。这个策略在元素不进行重新排序时比较合适,如果有顺序修改,diff 就会变慢。

@lkzwc lkzwc added the react label Sep 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant