react中componentWillReceiveProps()使用


定義: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是更新前的參數,通過判斷兩個值是否相同才執行相應的函數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM