爲什麼我們喜歡寫不componentWillMount頁眉或API請求或AJAX代碼componentDidMount。爲什麼我們喜歡寫在componentDidMount頁眉或API請求或Ajax代碼不componentWillMount
需要例如
爲什麼我們喜歡寫不componentWillMount頁眉或API請求或AJAX代碼componentDidMount。爲什麼我們喜歡寫在componentDidMount頁眉或API請求或Ajax代碼不componentWillMount
需要例如
簡單而明確的區別,因爲你需要的組件,以便與你從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的數據)。
謝謝你以非常簡單的方式解決了我的疑問。 – dxtmhjn
edgaromar90與構造函數相同的情況也。我們通常在初始渲染之前在構造函數和構造函數中調用臨時狀態。在初始渲染之前,constuctor和willMount都會調用,那麼爲什麼我們沒有在componentWillMount中使用 – dxtmhjn
「componentWillMount()在安裝發生之前立即被調用,它在render()之前調用,因此在此方法中同步設置狀態不會觸發re-避免在此方法中引入任何副作用或訂閱。「 - 來自[React doc](https://facebook.github.io/react/docs/react-component.html#componentdidmount) –
edgaromar90與構造函數相同的情況也。我們通常在初始渲染之前在構造函數和構造函數中調用臨時狀態。這兩個構造函數和willMount在初始渲染之前調用,那麼爲什麼我們不使用componentWillMount
可能的重複[爲什麼React文檔建議在componentDidMount中做AJAX,而不是componentWillMount?](https://stackoverflow.com/questions/) 27139366/why-do-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi) – lux