你不知道的React系列(五)key

132 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情

概念

key 帮助 React 识别哪些元素改变了,比如被添加或删除

新增元素插入到表头,那么更新开销会比较大

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

使用

map() 方法中的元素需要设置 key 属性

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => (
  <ListItem key={number.toString()} value={number} />
));

一个元素的 key 最好是唯一的字符串(比如 id)

  • 来自数据库的数据:  如果你的数据是从数据库中获取的,那你可以直接使用数据表中的主键,因为它们天然具有唯一性。
  • 本地产生数据:  如果你数据的产生和保存都在本地(例如笔记软件里的笔记),那么你可以使用一个自增计数器或者一个类似 uuid 的库来生成 key。

可以使用 index 作为 key(不推荐)

如果列表项目的顺序可能会变化,不要 index 用作 key 值

性能变差,组件状态问题

注意

key 不需要是全局唯一的

当我们生成两个不同的数组时,我们可以使用相同的 key 值

function Blog(props) {
const sidebar = (
  <ul>
    {props.posts.map((post) => (
      <li key={post.id}> {post.title}</li>
    ))}
  </ul>
);
const content = props.posts.map((post) => (
  <div key={post.id}>
    <h3>{post.title}</h3>
    <p>{post.content}</p>
  </div>
));
return (
  <div>
    {sidebar} <hr />
    {content}
  </div>
);
}

const posts = [
{ id: 1, title: "Hello World", content: "Welcome to learning React!" },
{ id: 2, title: "Installation", content: "You can install React from npm." },
];
ReactDOM.render(<Blog posts={posts} />, document.getElementById("root"));

key 会传递信息给 React ,但不会传递给你的组件

const content = posts.map((post) => (
  <Post key={post.id} id={post.id} title={post.title} />
));

不要在 JSX 中嵌入过多 map()

提取一个变量

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) => (
    <ListItem key={number.toString()} value={number} />
  ));
  return <ul>{listItems}</ul>;
}