一、列表组件没有key属性会warning?
1、key提高性能
当创建列表组件时,必须给每一个元素设置 key 属性,否则会有警告: a key should be provided for list items。如果元素没有key属性,React很难判断元素应该怎么渲染?如果元素有key值,那么React只对匹配key值的元素,进行更改等渲染操作,这样极高提升了运行性能。
二、列表组件使用说明
1、错误用法
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>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);
2、正确用法
function ListItem(props) {
// 正确!这里不需要指定 key:
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>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);
3、key值无法读取
key 值会传递给 React ,但不会传递给组件。如果需要使用 key 值,请用其他属性(譬如id):
# Post 组件可以读出 props.id,但是不能读出 props.key
const content = posts.map((post) =>
<Post
key={post.id}
id={post.id}
title={post.title} />
);
4、唯一性
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')
);