一、key的使用場景react
render() {
console.log(this.state);
return (
<div>
<h3>用戶列表</h3>
{this.state.users.map(u => <div key={u.id}>{u.id}:{u.name}</div>)}
</div>
);
}複製代碼
在項目開發中,key屬性的使用場景最多的是由數組動態建立的子組件的狀況,須要爲每一個子組件添加惟一的key屬性值。可參考實例demo,不設置key的話會出現下面這樣的warning。數組
"Warning: Each child in an array or iterator should have a unique 'key' prop.%s%s See https://fb.me/react-warning-keys for more information.%s" "複製代碼
二、key的做用bash
有了key屬性後,就能夠與組件創建了一種對應關係,react根據key來決定是銷燬從新建立組件仍是更新組件。
性能
注意:ui
https://www.tuicool.com/articles/UVvaMz
this