2017-04-04 75 views
1

我正在嘗試解決React有狀態組件和無狀態組件之間的區別。React組件從有狀態到無狀態(差異)

糾正我,如果我錯了:

所以,這是一個有狀態的組件:

import React from "react"; 

export class Mycomponent extends React.Component { 
    render() { 
     return (

      <div> 
       <p>My Component</p> 
      </div> 

     ); 
    } 
} 

和無狀態組件是如何將上面的有什麼不同?

+0

你有什麼考慮得出結論,這是一個有狀態組件?正如我現在看到的那樣,它不是有狀態的,也不是無狀態的。它只是靜態的。 – Leandro

+0

據我所知,無狀態組件僅從道具中獲取所有渲染數據。一旦你開始擺弄'this.state',你就得到了一個有狀態的組件。 – Leandro

+0

可能的重複:https://stackoverflow.com/questions/34512696/reactjs-difference-between-stateful-and-stateless –

回答

6

反應狀態滿組件通常具有類語法並擴展了反應組件基類。這使您可以訪問反應生命週期方法,如渲染,componentDidMount等。

另一方面,無狀態功能組件僅僅是返回jsx的函數。您不處於反應生命週期中,無法訪問組件基類方法。

這裏是無狀態功能組件的一些示例代碼。

export default function example() { 
    return (
     <h1>This is where the jsx goes</h1> 
    ) 
} 

我還應該指出,在一個無狀態的功能組件中,你可以通過將一個道具參數傳遞給函數來訪問道具,就像這樣。

export default function example(props) { 
    return (
     <h1>{props.person.firstName}</h1> 
    ) 
} 

,但在簡單地通過訪問this.props.whatever

+0

純功能組件是實現無狀態組件的一種方式。答案第一段中的關鍵詞是*通常*。將無狀態組件實現爲類('ES6'或'React.createClass')是完全有效的。所以,如果你有一個功能組件,它是一個無國籍的組件;但是您沒有功能組件這一事實並不一定意味着所討論的組件不是無狀態的。 – Leandro

+0

我認爲你所說的話是完全正確的,但是我認爲,我可能錯了,在反應區域中,無國籍功能組件被理解爲是一種功能而不是一個班級,因爲在一個班級中你可以有狀態,而在你不能的功能中。 –

+0

同樣,你說無國籍**功能**組件。當然,它必須使用一個函數來實現(因此是* functional *形容詞)。當然,它必須是無狀態的,因爲你不能在一個功能組件中訪問狀態。你可以說功能組件,而無狀態是隱含的。然而,在一個類中,你可以決定是否使用狀態,這是決定類組件是有狀態的還是無狀態的。 – Leandro

2

反應類,你必須的道具,你現在所擁有的是什麼類成分: https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components

的功能組件可以從字面上寫一個函數:

export default() => <h1>Hello World!</h1>; 

一類組分是類似於編寫OOP:

import React, { Component } from 'react'; 

export default class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     error: false, 
     loading: true 
    } 
    } 
    componentDidMount() { 
    const { data, status } = fetch(apiendpoint); // res.data 
    if (status !== 200) { 
     this.setState({ error: true }); 
     this._renderError(); 
    } 
    this.setState({ loading: false }); 
    } 
    _renderError() { 
    return <h1>Error!</h1>; 
    } 
    render() { 
    const component = loading ? 
     <Loading /> : 
     <h1>Hello {this.props.data}</h1>; 
     return component; 
    } 
} 

可以在類組件創建狀態通過構造,並通過使用setState()可以在組件級管理的狀態。希望這可以幫助您更好地瞭解差異!