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后面紧跟了两个小括号 不是只有一个小括号
本文介绍了一个React实战案例,讲解如何在点击按钮时动态地向数组中添加数据。重点强调了三个关键点:避免将数字作为字符串处理,正确地更新state以避免直接修改,以及使用map方法时的小括号注意事项。
830

被折叠的 条评论
为什么被折叠?



