問題描述:
在寫項目的時候碰到這樣一個問題
通過Link組件傳遞一個名爲“name”的state給子組件
並在子組件中把接受到的prop值賦給state
當父組件點擊Link進行傳值時
子組件收到prop並調用render函數
我們在render函數中打印出state值
發現state值始終沒有改變
問題分析
由於react的setstate方法是異步執行的,所以render函數並沒有收到更新的state值
解決方法
react生命週期中有這樣一個函數
componentWillReceiveProps
componentWillReceiveProps在初始化render的時候不會執行,它會在Component接受到新的狀態(Props)時被觸發,一般用於父組件狀態更新時子組件的重新渲染。
我們重寫這個函數
componentWillReceiveProps(nextProps) {
if(nextProps.location.state!=undefined){
this.setState({
activekey: nextProps.location.state.name
})
}
}
發現可以獲取到實時的數據了