问题引入
React中的setState是用来更新状态的重要工具,但是setState是同步的还是异步的,需要我们进行一定的探讨,接下来让我们好好研究研究。
使用setState的两种形式
- 函数形式的setState
test1 = () => {
// 函数形式的setState,函数形式的setState能够接收到两个参数,一个是state,另一个是props
this.setState(state => ({
count: state.count + 1}))
}
- 对象形式的setState
test2 = () => {
// 对象形式的setState
const count = this.state.count + 1;
this.setState({
count})
}
使用过setState之后能否立即获取到状态更新后的值
答案是不能。
test1 = () => {
// 函数形式的setState,函数形式的setState能够接收到两个参数,一个是state,另一个是props
this.setState(state => ({
count: state.count + 1}))
console.log('函数形式的setState更新后:',this.state.count);
}
如何立即获取到状态更新后的值
使用setState的第二个参数,这个参数接收的是一个回调函数,这个回调函数会在界面渲染之后调用。
test3 = () => {
this.setState(state => ({
count: state.count + 1}),() => {
console.log('函数形式的setState更新后:',this.state.count);
});
}
setState()更新状态是同步还是异步的?
回到我们要探讨的正题,setState()更新状态时同步的还是异步的?
判断setState()更新状态时异步还是同步的,主要是看执行setState的位置
- 在React控制的回调函数中(生命周期钩子,react事件监听回调)这种情况是异步的。
- 在非react控制的异步回调函数中(定时器回调/原生事件监听回调/promise回调)这种情况是同步的。
异步举例
- 在React事件回调函数中使用setState(异步的)
// React事件回调函数中
update1 = () => {
console.log('React事件回调函数更新之前:',this.state.count);
this.setState(state => ({
count: state.count + 1}))
console.log('React事件回调函数更新之后:',this.state.count);
}
- 在生命周期钩子函数中使用setState(异步的)
// 在生命周期钩子函数中
componentDidMount