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是更新前的参数,通过判断两个值是否相同才执行相应的函数。

 

posted @ 2020-05-09 13:03  鸡腿太小  阅读(5153)  评论(0编辑  收藏  举报