React的componentWillReceiveProps(nextProps)生命周期使用详解

官方文档解释:https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html

该方法当props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用

使用好处:在这个生命周期中,可以在子组件的render函数执行前获取新的props,从而更新子组件自己的state。 可以将数据请求放在这里进行执行,需要传的参数则从componentWillReceiveProps(nextProps)中获取。而不必将所有的请求都放在父组件中。于是该请求只会在该组件渲染时才会发出,从而减轻请求负担。componentWillReceiveProps在初始化render的时候不会执行,它会在Component接受到新的状态(Props)时被触发,一般用于父组件状态更新时子组件的重新渲染下面举个例子:

要实现的功能是Tab切换时,更新列表,这里每点击Tab则传一个typeCode值,假设是1,2,3,后端分页时接收三个参数,page、pageSize,typeCode,我遇到的问题是点击Tab时没有刷新,下边这样就能解决:

页面图:

React的componentWillReceiveProps(nextProps)生命周期使用详解_第1张图片

解决方法: 

state = { activeKey: '1' };
....
//父组件的:
 { this.setState({ activeKey: key }); }}>
            {lookupDatas.map((item, key) => (
              
                
              
            ))
            }
 
//子组件的:
  componentWillReceiveProps(nextProps){
    if(this.props.activeKey !== nextProps.activeKey){
      const params = {
        page: 1,
        pageSize: 10,
        typeCode: nextProps.activeKey,
        queryFilter: this.state.formValues,
      };
      this.getData(params);
    }
  }

 

你可能感兴趣的:(React)