import React, { PureComponent } from 'react'
export default class App extends PureComponent {
constructor(){
super();
this.state={
friends:[
{name:"lily",age:20},
{name:"tom",age:18},
{name:"chali",age:6},
]
}
}
render() {
return (
<div>
<h2>好友列表</h2>
<ul>
{
this.state.friends.map((item,index)=>{
return (
<li>
姓名:{item.name}
年龄:{item.age}
<button onClick={e=>this.increAge(index)}>age+1</button>
</li>)
})
}
</ul>
<button onClick={e=>this.increFriend()}>添加好友</button>
</div>
)
}
increFriend(){
const newFris=[...this.state.friends];
newFris.push({name:"mike",age:38});
this.setState({
friends:newFris
})
}
increAge(index){
const newFris=[...this.state.friends];
newFris[index].age += 1;
this.setState({
friends:newFris
})
}
}
注意:1.数字不要加引号,会变成字符串,那么 你后面使用方法年龄加1时 会在后面拼接1
2 不要直接改变this.state中的数据,而是用扩展运算符方式 复制一份;
3 map方法使用时注意map后面紧跟了两个小括号 不是只有一个小括号