React中的三种组件及其区别

版权声明:本文为博主原创文章,未经博主允许不得转载。原账号CreabineChen现已不用,所有博客均已迁移过来。 https://blog.csdn.net/Creabine/article/details/87364538

React中有三种生成组件的方式,分别是React.ComponentReact.PureComponentFunction,他们有什么异同呢?

参考资料:

React.Component

React.Component是最常使用的方式,我们经常用它来生成组件

// Component
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

React.PureComponent

React.PureComponent成为纯组件。

// PureComponent
class Welcome extends React.PureComponent {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

React.Component 和 React.PureComponent 的区别

首先需要知道React生命周期函数shouldComponentUpdate,这个函数返回一个布尔值,如果返回true,那么当props或state改变的时候进行更新;如果返回false,当props或state改变的时候不更新,默认返回true。这里的更新不更新,其实说的是执不执行render函数,如果不执行render函数,那该组件和其子组件都不会重新渲染。

其区别在于:

  1. 继承PureComponent时,不能再重写shouldComponentUpdate
  2. React.PureComponent基于shouldComponentUpdate做了一些优化,通过prop和state的浅比较来实现shouldComponentUpdate,也就是说,如果是引用类型的数据,只会比较是不是同一个地址,而不会比较具体这个地址存的数据是否完全一致。

什么时候使用PureComponent

PureComponent 真正起作用的,只是在一些纯展示组件上。复杂组件用了就跟Component一样了。因为PureComponent做的是浅比较,所以如果需要让对象或者数组的state变化引起render,那么一定要生成新的对象或数组,让它的引用改变,这样才能够触发render,否则是无效的:

class App extends PureComponent {
  state = {
    items: [1, 2, 3]
  }
  // 这样写的话 items 的引用没有变,不会触发render更新界面的
  handleClick = () => {
    const { items } = this.state;
    items.pop();
    this.setState({ items });
  }
  // 这样写 生成了一个新的数组,引用变了,就能够触发render了。
  handleClick = () => {
    const { items } = this.state;
    items.pop();
    this.setState({ items: [...items] });
  }
  render() {
    return (<div>
      <ul>
        {this.state.items.map(i => <li key={i}>{i}</li>)}
      </ul>
      <button onClick={this.handleClick}>delete</button>
    </div>)
  }
}

函数式组件Function

一个函数就是一个组件,return一份DOM解构,其特点是:

  1. 没有生命周期
  2. 没有this(组件实例)
  3. 没有内部状态(state)
    优点 :轻量,如果你的组件没有涉及到内部状态,只是用来渲染数据,那么就用函数式组件,性能较好。
// functional component
function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}

猜你喜欢

转载自blog.csdn.net/Creabine/article/details/87364538