setState不可变的力量
当使用了PureComponent继承,你直接赋值给你当前修改的值是不会更新的,具体代码如下:
import React, { PureComponent } from "react";
export default class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
friedInfo: [
{
name: "zhangsan",
age: 18,
sex: "男",
},
{
name: "lisi",
age: 19,
sex: "男",
},
{
name: "wangwu",
age: 20,
sex: "男",
},
],
};
}
render() {
const { friedInfo } = this.state;
return (
<div>
<ul>
{friedInfo.map((item) => {
return (
<li key={item.name}>
<span>{item.name}</span>
<br />
<span>{item.age}</span>
<br />
<span>{item.sex}</span>
</li>
);
})}
</ul>
<button onClick={() => this.addDataInfo()}>添加数据</button>
</div>
);
}
addDataInfo() {
const newData = { name: "TOM", age: 22, sex: "男" };
this.state.friedInfo.push(newData);
this.setState({
friedInfo:this.state.friedInfo
})
}
}
实际截图
如果用到了PureComponent 和shouldComponentUpdate优化的话,正确的做法就是
addDataInfo() {
const newData = { name: "TOM", age: 22, sex: "男" };
const copyFriedInfo = [...this.state.friedInfo]
copyFriedInfo.push(newData);
this.setState({
friedInfo: copyFriedInfo,
});
}
详细的过程 画了一幅图,
需求在年纪的每一行添加一个按钮 点击按钮+ 1
import React, { PureComponent } from "react";
export default class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
friedInfo: [
{
name: "zhangsan",
age: 18,
sex: "男",
},
{
name: "lisi",
age: 19,
sex: "男",
},
{
name: "wangwu",
age: 20,
sex: "男",
},
],
};
}
render() {
const { friedInfo } = this.state;
return (
<div>
<ul>
{friedInfo.map((item, index) => {
return (
<li key={item.name}>
<span>{item.name}</span>
<br />
<span>
<span>{item.age}</span>
<button onClick={() => this.addAge(index)}>年纪 + 1</button>
</span>
<br />
<span>{item.sex}</span>
</li>
);
})}
</ul>
<button onClick={() => this.addDataInfo()}>添加数据</button>
</div>
);
}
addDataInfo() {
const newData = { name: "TOM", age: 22, sex: "男" };
// 数据的解构 copy 一份
const copyFriedInfo = [...this.state.friedInfo];
copyFriedInfo.push(newData);
this.setState({
friedInfo: copyFriedInfo,
});
}
addAge(index) {
const newData = [...this.state.friedInfo];
newData[index].age += 1;
this.setState({
friedInfo: newData,
});
}
}
实际截图
[图片上传中...(image.png-eb7f2c-1640242382750-0)]