一曙搬、列表組件沒有key屬性會warning?
1鸽嫂、key提高性能
當創(chuàng)建列表組件時纵装,必須給每一個元素設(shè)置 key 屬性,否則會有警告: a key should be provided for list items据某。如果元素沒有key屬性橡娄,React很難判斷元素應(yīng)該怎么渲染?如果元素有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 應(yīng)該在這里指定:
<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 應(yīng)該在數(shù)組的上下文中被指定
<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 在兄弟節(jié)點間必須唯一赊颠,但全局不需要唯一格二。
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')
);