一、列表组件没有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.keyconst 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'));
参考文档
- React的列表组件必须要有key?