理解記憶總結: 父組件即將掛載(最外層的父組件都還沒准備進入,其內部的子組件當然更沒進入了) -》 子組件即將掛載 -》 子組件掛載完成(父內部都沒完成,父當然不能算完成) -》 父組件掛載完成。
類構造函數(class constructor) 是類初始化運行的,所以都在本組件的所有生命周期鈎子之前執行;
———————補充:2017.12.21———————————
頁面第一次加載的時候render方法位於componentWillMount之后,componentDidMount之前;之后在狀態機的驅動下,就只有render方法會再被執行
———————補充:2018.02.08———————————
我們知道單個組件的生命周期的函數執行順序是 componentWillMount -> render -> componentDidMount
但是函數執行順序並不意味着結束的順序,因為有異步這個死鬼(並無貶義),例子如下,
class Quiz extends Component { componentWillMount() { axios.get('/thedata').then(res => { //各種異步操作 this.setState({items: res.data}); }); } render() { return ( <ul> {this.state.items.map(item => <li key={item.id}>{item.name}</li> )} </ul> ); } }
這里有一個問題:當異步獲取數據時,異步函數會在所有同步函數(包括這種生命周期鈎子函數)執行完之后再執行,也就是說,組件在數據加載之前render函數會執行一次,此時 this.state.items 是未定義的。 這又意味着 ItemList 將 items 定義為 undefined,並且在控制台中出現錯誤 - “Uncaught TypeError: Cannot read property ‘map’ of undefined”。
其實這個問題的解決倒是不到,只需要:添加構造函數,並在其中初始化 this.state = { items: [] }
這里就這個細節希望大家稍加留意;
The End