关于React中setState回调函数

版权声明:本文为博主原创文章,未经博主允许不得转载。如果对你有帮助,那真是再好不过啦~ https://blog.csdn.net/SCU_Cindy/article/details/80989001

一般来说,React中只有通过setState方法才能改变页面初始时设置的state状态,并对页面进行从新渲染。其中,对页面的一些参数进行修改的时候,也可以使用setState的回调函数。setState(updater[, callback])

区别分析

0.初始状态

this.state = {
    test: 'test'
}

1.不使用回调函数

this.setState({
    test: 'hello world!'
});
console.log('1', this.state.test);
// 1, test

2.使用回调函数

this.setState({
    test: 'hello world!'
}, () => {
    console.log('2', this.state.test);
    // 2, hello world!
});

分析总结
1. updater是要改变的state对象,callback是state导致的页面重新渲染的回调,等价于componentDidUpdate.
2. 此处一定注意,setState是异步的,不保证数据的同步。
3. setState更新状态时可能会导致页面不必要的重新渲染,影响加载。

猜你喜欢

转载自blog.csdn.net/SCU_Cindy/article/details/80989001