定義:componentWillReceiveProps() 在生命周期的第一次render后不會被調用,但是會在之后的每次render中被調用 = 當父組件再次傳送props。
出現的現象:需要在props被改變時更新一些東西,所以使用了componentWillReceiveProps方法,但是卻發現該方法總是在各種沒有改變props的情況下被調用。
解決:
父子間傳遞過去一個id
<VisitRegister id={this.state.item.id}></VisitRegister>
子組件根據id變化執行想要執行的方法
componentWillReceiveProps(nextProps){
if(nextProps.id !=this.props.id){
this.setState({
id: nextProps.id
},()=>this.onSearch()
);
}
}
解釋:nextProps是componentWillReceiveProps周期函數自帶的參數,代表更新后的參數,this.props.id是更新前的參數,通過判斷兩個值是否相同才執行相應的函數。
