henrycjchen / blog

henry's blog
https://henrycjchen.github.io/blog/docs/
0 stars 0 forks source link

React.PureComponent vs React.Component #1

Open henrycjchen opened 4 years ago

henrycjchen commented 4 years ago

react 中有个生命钩子:shouldComponentUpdate,用于判断是否需要渲染当前组件(默认情况下 react 会对全部组件进行 diff 运算,这里可以减少 diff 的工作量,setState -> shouldComponentUpdate -> render.fn -> diff -> vdom -> real.render) 使用示例:

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

React.PureComponent 会自动触发 shouldComponentUpdate 对 props/state 的前后状态进行浅比较,以提高渲染效率