React.js 無狀態元件 vs 有狀態元件


理解 React 元件中無狀態和有狀態的區別

在狀態管理文章中,我們學習瞭如何在 React 中處理狀態變化。

  • 無狀態元件是簡單的函式式元件,沒有本地狀態,但請記住,React 中也有一種 Hook 可以為函式式元件新增狀態行為。
  • 有狀態元件可以包含狀態物件和事件處理函式,以及使用者操作。
  • 無狀態元件本質上是純函式,執行非常特定的任務。
import React from 'react';
const player = (props) => {
   return (
      <div>
         <p>I'm a Player: My name {props.name} and my score is
         {props.score}</p>
         {props.children}
      </div>
   );
}
export default player;

上面就是一個這樣的函式式元件,它只顯示從另一個元件傳遞的 props 屬性。我們可以從函式式元件呼叫位於類元件(容器)中的事件處理函式。

容器是指包含一些本地狀態或事件或使用者操作的元件。

我們可以在函式式元件中新增一些邏輯動態程式碼,但不能修改狀態或應用程式資料。

從函式式元件傳遞方法引用

在動態輸出文章中,我們已經瞭解瞭如何從父元件傳遞屬性到子函式式元件。類似地,我們可以新增方法引用。

import React, {Component} from 'react';
import './App.css';
import Player from './Player'
class App extends Component {
   state = {
      players:[
         {name: 'Smith', score:100 },
         {name: 'David', score:90},
         {name: 'Phil', score:80}
      ],
   otherObject:'Test'
}
switchPlayerHandler = () =>{
   this.setState({players:[
      {name: 'Smith', score:200},
      {name: 'David', score:290},
      {name: 'Phil', score:380}]});
   }
   render(){
      return (
         <div className="App">
            <button onClick={this.switchPlayerHandler}>
               Switch Player
            </button>
            <Player name={this.state.players[0].name}
               score={this.state.players[0].score}
               click={this.switchPlayerHandler}/>
            <Player name={this.state.players[1].name}
               score={this.state.players[1].score}
               click={this.switchPlayerHandler}>
               Plays for Australia
            </Player>
            <Player name={this.state.players[2].name}
               score={this.state.players[2].score}
               click={this.switchPlayerHandler}/>
         </div>
      );
   }
}
export default App;

觀察我們傳遞了一個方法引用

<Player name={this.state.players[2].name}
   score={this.state.players[2].score}
   click={this.switchPlayerHandler}/>

我們可以在函式式元件中使用它,類似於 onClick 函式呼叫

import React from 'react';
const player = (props) => {
   return (
      <div>
         <p onClick={props.click}>I'm a Player: My name {props.name} and my score is {props.score}            </p>
         {props.children}
      </div>
   );
}
export default player;

向函式式元件中的方法引用傳遞引數

<button onClick={this.switchPlayerHandler.bind(this,'John','Test')}>
   Switch Player
</button>

使用上述語法,我們可以將 this 作為類繫結的第一個引數,其餘引數是我們想要傳遞的值。

switchPlayerHandler = (newName,secondName) =>{
   this.setState({players:[
      {name: newName, score:200},
      {name: secondName, score:290},
      {name: 'Phil', score:380}
   ]});
}

傳遞的值可以在函式中使用,如上所示。

還有一種替代方法可以傳遞方法引數。

onClick={ () => this.switchPlayerHandler('Michel','Stark') }

以上是匿名函式呼叫。它的效果相同。這種方法不如第一種方法有效,因為 React 在第二次匿名函式呼叫時會進行一些渲染。如果我們不考慮效能損失,則取決於情況。

狀態或應用程式資料的修改應該在少數幾個選定的元件中完成,以避免複雜性。

更新於: 2019年9月4日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告