2017-05-29 67 views
0

我使用react創建了一個類似於twitter的框。我在查看反應文檔中發現的幾個組件生命週期,但不知道應該使用哪一個來改善我的代碼性能:componentDidMountcomponentWillMountcomponentDidMount或componentWillMount我需要使用哪一個

當我在我的文本框中鍵入內容時,我在控制檯中看到一個打印文本框值的更新。任何人都可以幫助我理解在這種情況下使用哪種方法?

https://jsfiddle.net/c9zv7yf5/2/

class TwitterBox extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { enteredTextBoxvalue : '' }; 
     this.handleChange = this.handleChange.bind(this); 

    } 

    handleChange(event) { 
    this.setState({enteredTextBoxvalue: event.target.value}); 

    if((event.target.value).length > 3) { 

     this.setState({className : 'wholeContainer'}); 
     //console.log("long characters"); 
    } 
    } 

    render() { 
     return (<div>Hello {this.props.name} 
       <textarea className={this.state.className} 
       value={this.state.enteredTextBoxvalue} 
       onChange = {this.handleChange}> 
       there should be only 140 characters 
      </textarea> 
     </div>); 
    } 
} 

ReactDOM.render(
    <TwitterBox name="World" />, 
    document.getElementById('container') 
); 
+0

的官方文檔實際上解釋非常好使用哪種「生命週期法」,其中的情況:https://facebook.github.io/react /docs/react-component.html –

+0

@TomVanRompaey嘿我讀通過文件,但不知道何時實施...這將是偉大的,如果你幫我... –

回答

0

componentWillMount被稱爲組件被呈現的右前。 componentDidMount在組件被渲染後立即被調用。

如果您需要準備數據,請使用componentWillMount。 componentDidMount在組件呈現之後發送api調用或抓取數據中被廣泛使用,並強烈建議使用它。

+0

你好,你可以在我的代碼更新...這是混亂 –

0

componentWillMount:

該功能被稱爲右前組件的第一渲染,所以乍一看這似乎是把數據取邏輯

componentDidMount一個完美的地方:

使用componentDidMount清楚地表明,直到初始渲染之後纔會加載數據。這提醒您正確設置初始狀態,所以最終不會導致導致錯誤的未定義狀態。

+0

你好,你可以在我的代碼更新...這很容易 –

0

作爲你的問題的一部分是關於性能,你可以考慮看看shouldComponentUpdateavoid reconciliation

在安裝發生之前立即調用componentWillMount。它在render()之前調用。

在安裝組件後立即調用componentDidMount。

+0

你好,你可以更新我的代碼...這很混亂 –

0

componentWillMount

  • 組件即將呈現,扮演constructor
  • 同樣的作用存在DOM組員但你不能做任何涉及DOM 操作
  • 調用setState()同步會不觸發 重新渲染,因爲組件尚未渲染
  • 我不會在這裏推薦調用異步/api請求(在技術上,我們無法保證,他們將完成組件將被安裝之前,在這種情況下,您的組件將不會被重新繪製到應用這些數據)

componentDidMount

  • 組件已被渲染,它已經位於DOM中
  • 您可以在這裏執行涉及DOM元素的操作(例如,初始化第三方插件)
  • 調用異步/api請求等
+0

你好,你可以更新我的代碼....這是混亂 –

相關問題