React(二):类组件、函数式组件

Component(组件)能够是类组件(class component)、函数式组件(function component)。数组

一、类组件:
bash

一般状况下,咱们会使用ES6的class关键字来建立React组件。
函数

a、类组件分为普通类组件(React.Component)以及纯类组件(React.PureComponent)。性能

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

b、React.Component和React.PureComponent区别
优化

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

区别:this

  • 一、继承PureComponent时,不能再重写shouldComponentUpdate
  • 二、React.PureComponent基于shouldComponentUpdate作了一些优化,经过prop和state的浅比较来实现shouldComponentUpdate,也就是说,若是是引用类型的数据,只会比较是否是同一个地址,而不会比较具体这个地址存的数据是否彻底一致。

class ListOfWords extends React.PureComponent {
 render() {
     return <div>PureComponent渲染结果:{this.props.words.join(',')}</div>;
 }
}
class WordAdder extends React.Component {
 constructor(props) {
     super(props);
     this.state = {
         words: ['marklar']
     };
     this.handleClick = this.handleClick.bind(this);
 }
 handleClick() {
     // This section is bad style and causes a bug
     const words = this.state.words;
     words.push('marklar');
     this.setState({words: words});
 }
 render() {
    // slice() 方法返回一个新的数组对象
     return (
         <div>
             <button onClick={this.handleClick}>click</button>
            <div>Component渲染结果:{this.state.words.join(',')}</div>
         <ListOfWords words={this.state.words} />
             <ListOfWords words={this.state.words.slice(0)} />
         </div>
     );
 }
}
ReactDOM.render(
  <WordAdder />,
  document.getElementById('root')
);复制代码

在 CodePen 上尝试。
spa

二、函数式组件:
code

一个函数就是一个组件,return一份DOM解构
特色:
1.没有生命周期,也会被更新并挂载,可是没有生命周期函数
2.没有this(组件实例)
3.没有内部状态(state)
优势 :轻量,若是你的组件没有涉及到内部状态,只是用来渲染数据,那么就用函数式组件,性能较好。复制代码
// functional component
function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}复制代码
//组合组件
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);复制代码

三、函数式组件与基于Class声明的组件比较component

  • 不须要声明类,能够避免大量的譬如extends或者constructor这样的代码

  • 不须要显示声明this关键字,在ES6的类声明中每每须要将函数的this关键字绑定到当前做用域,而由于函数式声明的特性,咱们不须要再强制绑定。

  • 更佳的性能表现:由于函数式组件中并不须要进行生命周期的管理与状态管理,所以React并不须要进行某些特定的检查或者内存分配,从而保证了更好地性能表现。

const Text = (props) =>
  <p>{props.children}</p>;

class App extends React.Component {
  render() {
    return <Text>Hello World</Text>;
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);复制代码

在 CodePen 上尝试。