avatar

目录
react setState更新机制

setState 更新机制

1.setState 传参方式

setState(obj||func,func)setState可以接受俩个参数,第一参数是代表新state的对象或者返回新state对象的函数,第二个参数是更新state后的回调函数

1.对象

Javascript
handel = ()=>{
this.setState({num: this.state.num - 10})
this.setState({num: this.state.num + 1}) // 只执行此句
}

在组件的方法中多次以传参对象的方式调用setState会导致覆盖合并,只执行最后一个setState,这是由react本身的性能机制决定:

setState并不是同步的,react会将多个setState合为一个进行更新,减少render()的调用,提高性能

然而在平常方法中,我们一般只调用一次setState

2.函数

setState如果第一个参数传函数可以在函数中拿到新state的值,

Javascript
chang = () => {
this.setState((preState) => { // state旧值
const newNum = preState.num + 1
console.log(newNum)
return {num: newNum}
})
};

多次setState会合并为一次,进行render更新

Javascript
change = () => {
this.setState((state) => ({
num: state.num + 1
}));
console.log("num", this.state.num);
this.setState((state) => ({
num: state.num - 1
}));
};

2. setState 更新方式

1. 异步

React 提供的事件(比如 onClick)调用setState是异步更新的,这是有react 本身的性能机制决定的,

但我们可以通过setState的回调拿到更新后的state

Code
handel = () => {
// 对象参数
this.setState({ num: this.state.num - 10 });
console.log("num1", this.state.num);
this.setState({ num: this.state.num + 1 },()=>{
console.log(this.state.num)
});
};

2.同步

绕过React通过addEventListener直接添加的事件处理函数,还有通过setTimeout/setInterval产生的异步调用,在这些情况下,setState是同步更新并render页面的

Javascript
update = () => {
// 同步调用
setTimeout(() => {
this.setState({ num: this.state.num + 1 });
console.log("num0", this.state.num);
this.setState({ num: this.state.num + 1 });
console.log("num1", this.state.num);
});
};

代码链接

参考文章:

  1. setState何时同步更新状态
  2. react的setState到底是同步还是异步
  3. react之setState运行机制
文章作者: GRIT
文章链接: https://grit0821.github.io/Blog/2020/10/29/react-setState%E6%9B%B4%E6%96%B0%E6%9C%BA%E5%88%B6/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Grit's World