1. 程式人生 > >在react開發過程中由於setState的非同步特性,獲取最新state遇到問題

在react開發過程中由於setState的非同步特性,獲取最新state遇到問題

 1 //在父元件內 改變 state.dataSetValue
 2 <Select onChange={(value) => {
 3              this.setState({
 4                    dataSetValue: value
 5              });}}>
 6     <option>1</option>    
 7     <option>2</option>
 8 </Select>
 9 
10 // 將state.dataSetValue屬性傳給DataSetSubDirectory子元件
11 <DataSetSubDirectory 12 dataSetValue={this.state.dataSetValue} /> 13 14 // 在子元件生命週期函式componentWillReceiveProps內可以獲取最新的props 15 componentWillReceiveProps(nextProps) { 16 console.log(nextProps.dataSetValue); 17 this.handelGetDataSetSubDirectory(nextProps.dataSetValue); 18 }

重點:在react的componentWillReceiveProps(nextProps)生命週期中,可以在子元件的render函式執行前獲取新的props,從而更新子元件自己的state。