import ReactDOM from 'react-dom/client';
import React, { Component } from 'react'
export default class Ikun extends Component {
constructor(props) {
super(props);
this.state = {
cuount: 0
}
}
render() {
return (
<div>
<button onClick={() => this.click()}>点击</button>{this.state.cuount}
</div>
)
}
click = () => {
this.setState({
cuount: this.state.cuount + 1
}, () => {
console.log("放在回调中:" + this.state.cuount)
})
console.log("放在外部同步执行1:" + this.state.cuount)
this.setState({
cuount: this.state.cuount + 1
})
console.log("放在外部同步执行2:" + this.state.cuount)
this.setState({
cuount: this.state.cuount + 1
})
console.log("放在外部同步执行3:" + this.state.cuount)
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Ikun />
);
It should be noted that this.setState() is asynchronous, and multiple setStates are executed synchronously at the same time and will be merged. If you need to get updated real-time data, you need to get it from the callback function in the second parameter of this.setState()