Bootstrap

1分钟带你入门 React SCU、memo、pureCom

前言: 话说React的性能优化,你也许能想到shouldComponentUpdate这个钩子函数,如果不了解,那么你更加需要看啦

如果你对React生命周期一无所知的话,我建议你先看看这个

sholdComponentUpdate

它的逻辑是这样的;当这个钩子函数返回true就会执行组件的render函数,否则就不会执行,它的默认值是返回true

换句话说,React把组件是否刷新的权利交给了我们这些开发者

...  
shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

...

需要注意的是,nextState.xxx 就是 你调用this.setState({xxx: ???}) 传入的这个对象,如果你传入的这个对象的内存地址和this.state.xxx的内存地址相同的话,那么这个函数永远都会返回false

错误示例:

...
  handleCount = () => {
    this.state.list.push(Math.random()) // !!!想这样直接修改数组原数组的
    this.setState({list: this.state.list})
  }

  shouldComponentUpdate(nextProps, nexState) {
    return nexState.list !== this.state.list // 这里永远都会返回false
  }
...

正确示例:

...
  handleCount = () => {
    this.setState({list: this.state.list.concat(Math.random())}) // 返回一个新的数组
  }

  shouldComponentUpdate(nextProps, nexState) {
    return nexState.list !== this.state.list
  }
...

React.pureComponent

这个API的目的就是为了做性能优化和减少开发者的代码工作量;它的实现原理就是在shouldComponentUpdate这个函数里面分别对nextProps和nextState做了浅层对比。用法如下:

...
class Demo extends React.pureComponent {
	...
  shouldComponentUpdate(nextProps, nextState) { // 这个函数不需要你手写,这里只是为了展示
		.... // 这里React自动做了浅层对比
  }
}

React.memo

为了适应React推行的全面使用function组件,这个API应运而生!

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) { // 默认不用谢,除非你要自定义对比规则
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

小结

  • shouldComponentUpdate

  • 这个生命周期钩子函数式是React留个开发做性能优化的一个口子,它默认值是返回true,当返回true时,组件会执行render函数,也就是React无论你的数据是否更之前的相同,它都是无脑更新组件的

  • 若果你想进行一些性能优化,例如减少不必要更新,可以在这个函数里面做文章

  • 值得注意的是,在调用this.setState时,传递的内存地址要不相同,否则不会进行页面更新

  • React.pureComponent 本质上就是React在shouldComponentUpdate里面自动做了浅层的数据比较,提高开发体验

  • React.memo的作用和React.pureComponent相同,为了满足function组件而设计的

参考: