React 中的 setState

React 中的 setState 有三个注意点

  1. setState 并不会立即更新
  2. setState 会引发组件的重新绘制
  3. 多个 setState 会合并执行

这三个点也可以合在一起来说,首先,我们应该意识到,我们想要更新 state 的值,除了state本身的数值要改变,另外render也必须要执行,这才能让state的更新有意义。
所以,state的更新会引起生命周期发生变化。这4个函数依次被调用。

  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

在 render函数被调用的时候,this.state才得到更新,即使 shouldComponentUpdate 返回了 false,state 也依旧会更新。
正是因为state会引起生命周期的变化,所以为了优化性能,React会把更新的 state 的操作 排成一个队列,一次性将对列中的state属性更新。
当然,为了解决 setState 不会自动更新这个坑,setState 也有解决方法,它设置了一个回调函数,当 state 中的属性更新后调用。调用函数也可为空。

this.setState({ 
name: 'newName' },
this.changeName);

changeName = () => {
const { name } = this.state;
console.log(name);
}

以上是对象式的setState用法,下面再说一种函数式的setState用法。

// 第一种
this.setState((preState, props) => {
    return {name: props.name}
});

// 第一种的延伸
this.setState((preState, props) => {
     console.log(preState)
     return {name: 'newName'}
 }, () => console.log(this.state.name));
 
// 第二种
this.setState((preState, props) => ({
    name: preState.name
}));

参考链接:
https://zhuanlan.zhihu.com/p/25954470
https://blog.csdn.net/u011272795/article/details/80882567

猜你喜欢

转载自blog.csdn.net/kelly0721/article/details/86524106