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