2017-08-24 15 views

回答

1

簡單而明確的區別,因爲你需要的組件,以便與你從API獲取數據來填充它被渲染,您應該使用componentDidMount()

componentWillMount(){ 
    //Fetch API and set the State 
} 

render(){ 
    return(<div>{this.state.myData}</div>) 
} 

componentWillMount()火了<div>尚未呈現(不會在DOM的時刻存在)。

當在另一方面使用componentDidMount()。渲染方法運行首先在DOM創建<div>元素,然後componentDidMount()運行後,獲取數據,您將state和創建組件的重新渲染。這就是我們使用componentDidMount()從API獲取數據的原因。你可以找到更多的信息here

警告:您應該驗證狀態這樣你就不會得到undefined第一時間的成分是渲染(無來自API的數據)。

+0

謝謝你以非常簡單的方式解決了我的疑問。 – dxtmhjn

+0

edgaromar90與構造函數相同的情況也。我們通常在初始渲染之前在構造函數和構造函數中調用臨時狀態。在初始渲染之前,constuctor和willMount都會調用,那麼爲什麼我們沒有在componentWillMount中使用 – dxtmhjn

+0

「componentWillMount()在安裝發生之前立即被調用,它在render()之前調用,因此在此方法中同步設置狀態不會觸發re-避免在此方法中引入任何副作用或訂閱。「 - 來自[React doc](https://facebook.github.io/react/docs/react-component.html#componentdidmount) –

0

edgaromar90與構造函數相同的情況也。我們通常在初始渲染之前在構造函數和構造函數中調用臨時狀態。這兩個構造函數和willMount在初始渲染之前調用,那麼爲什麼我們不使用componentWillMount

相關問題