image.png
两种方式渲染并进行修改数据
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
// 挂载
componentDidMount() {
// 方式一:
/**
* 1.使用this.setState进行更新数据进行给count赋值
* 2.在回调中可以得到赋值后最新的值,因为setState是异步的
*/
this.setState(
{
count: this.state.count + 1
},
() => {
console.log(this.state.count, 'start'); //1
}
);
console.log(this.state.count, 'end'); //0
// 方式二:
// this.setState(
// (prevState, prevProps) => ({
// count: prevState.count + 1
// }),
// () => {
// console.log(this.state.count, 'start'); //1
// }
// );
// console.log(this.state.count, 'end'); //0
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
</div>
);
}
}
本次就分享到这里,喜欢的请关注支持下,期待后期更多内容
网友评论