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 上嘗試。

相關文章
相關標籤/搜索