我們在map遍歷的很適合王浴,很多時候都要在虛擬dom上加上一個key值脆炎,大多數(shù)都直接用的index作為key值氓辣,這里來討論一點。
為什么列表的key盡量不要用index
這里給出2篇參考:
- http://jsbin.com/wohima/edit?js,output
- http://taobaofed.org/blog/2016/08/24/react-key/?utm_source=tuicool&utm_medium=referral
簡單來說:當數(shù)組中的數(shù)據(jù)發(fā)生變化時:React會比較更新前后的元素Key值几蜻,如果相同則更新喇潘,如果不同則銷毀之前的梭稚,重新創(chuàng)建一個。
一個小例子:
function ListItem({id, name, age}) {
return <li>{id}--{name}--{age}---<input type="text"/></li>;
}
class PersonList extends React.Component {
constructor(props) {
super(props);
this.state = {
persons: [
{id: 1, name: 'Tom', age: 12},
{id: 2, name: 'Jack', age: 13}
]
};
this.update = this.update.bind(this);
}
update() {
let persons = this.state.persons;
persons.unshift({id: 3, name: 'Bob', age: 14})
this.setState({persons})
}
render() {
const persons = this.state.persons;
const listItems = persons.map((person, index) =>
<ListItem key={person.id} {...person}/>
);
const listItems2 = persons.map((person, index) =>
<ListItem key={index} {...person}/>
);
return (
<div>
<h2>使用id作為key</h2>
<ul>
{listItems}
</ul>
<h2>使用index作為key</h2>
<ul>
{listItems2}
</ul>
<button onClick={this.update}>首位添加一個人</button>
</div>
);
}
}
ReactDOM.render(
<PersonList/>,
document.getElementById('root')
);
輸出:
image.png
添加了一個人之后:
image.png