React.Component和PureComponent区别

3,283 阅读4分钟

React.Component和React.PureComponent有一个不同点

除了为你提供了一个具有浅比较的shouldComponentUpdate方法,PureComponent和Component基本上完全相同。当props或者state改变时,PureComponent将对props和state进行浅比较。另一方面,Component不会比较当前和下个状态的props和state。因此,每当shouldComponentUpdate被调用时,组件默认的会重新渲染。

浅比较101

当把之前和下一个的props和state作比较,浅比较将检查原始值是否有相同的值(例如:1 == 1或者ture==true),数组和对象引用是否相同。

从不改变

您可能已经听说过,不要在props和state中改变对象和数组,如果你在你的父组件中改变对象,你的“pure”子组件不将更新。虽然值已经被改变,但是子组件比较的是之前props的引用是否相同,所以不会检测到不同。

因此,你可以通过使用es6的assign方法或者数组的扩展运算符或者使用第三方库,强制返回一个新的对象。

存在性能问题?

比较原始值值和对象引用是低耗时操作。如果你有一列子对象并且其中一个子对象更新,对它们的props和state进行检查要比重新渲染每一个子节点要快的多。

PureComponent解决方法

不要在render的函数中绑定值

假设你有一个项目列表,每个项目都传递一个唯一的参数到父方法。为了绑定参数,你可能会这么做:

<CommentItem likeComment={() => this.likeComment(user.id)} />

这个问题会导致每次父组件render方法被调用时,一个新的函数被创建,已将其传入likeComment。这会有一个改变每个子组件props的副作用,它将会造成他们全部重新渲染,即使数据本身没有发生变化。

为了解决这个问题,只需要将父组件的原型方法的引用传递给子组件。子组件的likeComment属性将总是有相同的引用,这样就不会造成不必要的重新渲染。

<CommentItem likeComment={this.likeComment} userID={user.id} />

然后再子组件中创建一个引用了传入属性的类方法:

class CommentItem extends PureComponent {
  ...
  handleLike() {
    this.props.likeComment(this.props.userID)
  }
  ...
}

不要在render方法里派生数据

考虑一下你的配置组件将从一系列文章中展示用户最喜欢的十篇文章。

render() {
  const { posts } = this.props
  const topTen = posts.sort((a, b) => b.likes - a.likes).slice(0, 9)
  return //...
}

每次组件重新渲染时topTen都将有一个新的引用,即使posts没有改变并且派生数据也是相同的。这将造成列表不必要的重新渲染。

你可以通过缓存你的派生数据来解决这个问题。例如,设置派生数据在你的组件state中,仅当posts更新时它才更新。

componentWillMount() {
  this.setTopTenPosts(this.props.posts)
}
componentWillReceiveProps(nextProps) {
  if (this.props.posts !== nextProps.posts) {
    this.setTopTenPosts(nextProps)
  }
}
setTopTenPosts(posts) {
  this.setState({
    topTen: posts.sort((a, b) => b.likes - a.likes).slice(0, 9)
  })
}

如果你正在使用Redux,可以考虑使用reselect来创建"selectors"来组合和缓存派生数据。

案例分析

这里创建 Greeting 的组件,其中我们用 setInterval 每间隔 2 秒就更新状态title一次,然后在 6 秒后调用 clearInterval 方法来取消这个打点器。

import React, {Component,Fragment} from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Title extends React.Component {
  render() {
      console.log('rendering tut title ...');
    return (
      <div>
        <span>{this.props.name}</span>
      </div>
    )
  }
}
class Subtitle extends React.Component {
  render() {
      console.log('rendering sub tittle...')
    return (
        <div>
        <span>{this.props.name}</span>
      </div>
    )
  }
}
class Content extends  React.PureComponent {
  render() {
      console.log('rendering content ...');
    return (
      <div>
        <span>{this.props.name.join(',')}</span>
      </div>
    )
  }
}
export default class Greeting extends React.Component {
  constructor(props){
      super(props);
      this.state = {
          title:Math.random(),
          subTitle:Math.random(),
          content:['hello'],
      }
  }

  componentDidMount(){
      const id = setInterval(() => this.setState({title: Math.random()}),2000);
      setTimeout(()=> clearInterval(id),6000);  
  }
  render() {
    return (
      <Fragment>
        <Title name={this.state.title}/>
        <Subtitle name={this.state.subTitle}/>
        <Content name={this.state.content}></Content>
      </Fragment>
    )
  }
}


ReactDOM.render(
  <Greeting />,
  document.getElementById('root')
);

可以从结果看出来,其实每秒值只更新状态state的title值,应该只需要渲染子组件Title,但同时也渲染子组件Subtitle,Content,这是我们不期望的。

rendering tut title ...
rendering sub tittle...
rendering content ...
rendering tut title ...
rendering sub tittle...
rendering content ...
rendering tut title ...
rendering sub tittle...
rendering content ...
rendering tut title ...
rendering sub tittle...
rendering content ...

因此我们可以在子组件TutSubtitle,Content中使用React.PureComponent或者shouldComponentUpdate来进行浅比较,就会阻止子组件不必要的渲染。

class TutSubtitle extends React.PureComponent {
//   使用React.PureComponent或者shouldComponentUpdate,但两者不能同时使用,否则会报警告
//   shouldComponentUpdate(nextProps, nextState, nextContext) {
//     console.log(nextProps,nextState, this.props)
//     return nextProps.name !== this.props.name;
// }
  render() {
      console.log('rendering sub tittle...')
    return (
        <div>
        <span>{this.props.name}</span>
      </div>
    )
  }
}
class Content extends  React.PureComponent {
  render() {
      console.log('rendering content ...');
    return (
      <div>
        <span>{this.props.name.join(',')}</span>
      </div>
    )
  }
}

更新title状态,只渲染Title组件,这正是我们所期望,输出结果:

rendering tut title ...
rendering sub tittle...
rendering content ...
3 rendering tut title ...

结束语

因此意味着相比于Component,PureCompoent的性能表现将会更好。但使用PureCompoent要求满足如下条件:

  1. props和state都必须是不可变对象(immutable object)。
  2. props和state不能有层级嵌套的结构,(否则对子层级的改变无法反映在浅拷贝中)。
  3. 如果数据改变无法反应在浅拷贝上,则应该调用forceUpdate来更新Component。
  4. 一个PureComponent的子Component也应当是PureComponent。

参考文章

何时使用Component还是PureComponent?
React PureComponent 和 Component 区别
React 的 PureComponent Vs Component