注释掉 this.setState({val: this.state.val + 6}) 时:
不注释掉 this.setState({val: this.state.val + 6}) 时:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(porps) {
super(porps);
this.state = {
val: 0
};
}
componentDidMount() {
this.setState(this._increment);
this.setState(this._increment);
//this.setState({val: this.state.val + 6});
this.setState(this._increment);
console.log('componentDidMount:')
console.log(this.state);
}
_increment(state, props){
console.log('_increment:')
console.log(state);
return {val: state.val + 1};
}
render() {
console.log('render:')
console.log(this.state);
return (
<div className="App">
<div>{this.state.val}</div>
</div>
);
}
}
export default App;
this.setState()是异步的,render()会等这几个setState的异步函数都执行完(包括需要异步执行的代码)才会执行