<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
/*
慢动作回放 -- 使用index作为key
*/
class Person extends React.Component{
state = {
persons:[
{id:1,name:'hujesse',age:18},
{id:2,name:'hujesse83',age:20},
]
}
add = ()=>{
const {persons} = this.state;
const p = {id:persons.length+1,name:'ellysong',age:18};
this.setState({persons:[p,...persons]})
console.log(persons)
}
addV2 = ()=>{
const {persons} = this.state;
const p = {id:persons.length+1,name:'ellysong',age:18};
this.setState({persons:[p,...persons]})
console.log(persons)
}
render(){
return(
<div>
<h1>展示员工信息</h1>
<button onClick={this.add}>添加最爱的员工</button>
<h3>使用数组index作为索引值,每次插入都会导致index的改变,导致全局虚拟dom都要替换</h3>
<ul>
{
this.state.persons.map((personObj,index)=>{
return <li key={index}> 我的索引为index=={index}==id:{personObj.id}==={personObj.name}==={personObj.age} <input type="text"/></li>})
}
</ul>
<hr/>
<button onClick={this.addV2}>添加最爱的员工 Verson2</button>
<h3>使用数据唯一标识id作为索引值,id唯一</h3>
<ul>
{
this.state.persons.map((personObj)=>{
return <li key={personObj.id}>我的便利索引为id=={personObj.id} id
诶 {personObj.id}==={personObj.name}==={personObj.age} <input type="text"/></li>})
}
</ul>
</div>
)
}
}
ReactDOM.render(
<Person/>,
document.getElementById('example')
);
</script>
</body>
</html> ```