React生命周期

     React生命周期
近期做了一个项目脉冲云,脉冲云是一个基于敏捷思想,提高开发效率的工具;开发/运维一体化的协作平台。脉冲云的前端用的是react技术,下面简单介绍下在开发过程中自己对于react生命周期的理解,以及一些运用。

constructor(props)
构造函数,在创建组件的时候调用一次,可以在这里初始化state或者其他值

  constructor(props) {
    super(props);
    this.state = {
      disabled: false
    };
    this.log = “log”;
  }

componentWillMount()
在组件挂在前调用,且只会调用一次(state或者props发生改变并不会触发),这里可以修改state或者做异步请求。此处如更改state会在render()渲染时获取修改后的state

 componentWillMount() {
    //this.setState({xxx})
    //异步请求
  }

componentDidMount()
初始化渲染后执行,这时可以获取相应的DOM节点。这里可以挂载一些其他的插件之类的,也可以执行异步请求

componentDidMount() {
    //挂载其他插件
    //异步请求
  }

componentWillReceiveProps(nextProps)
组件在接受到新的props时执行,nextProps是接受到的新的props,可以通过this.props获取老的props。例如:当父组件传入新的props的时候可以在此做些简单的处理

componentWillReceiveProps(nextProps){
    let params = this.params;
    let nextParams = nextProps.params;
 if (params.sub !== nextParams.sub){
       //简单的逻辑处理
  }
}

shouldComponentUpdate(nextProps, nextState)
组件在接受新的props或者state执行,默认返回值true,为false时不会重新渲染。nextProps是接受到的新的props,可以通过this.props获取老的props。nextState是接受到的新的state,可以通过this.state获取老的state。例如:当父组件传入的props与老的props相同时不重新渲染。
shouldComponentUpdate(nextProps, nextState){
    let params = this.params;
    let nextParams = nextProps.params;
    let state = this.state;
    let nextState = nextState.params;
 if (params.sub === nextParams.sub){
       return false;
  }
 if (state === nextState.sub){
       return false;
  }
    return true;
}

componentWillUpdate()
组件渲染前执行,接受新的props、state或者调用forceUpdate()

componentDidUpdate()
组件每次渲染都会执行,可以获取相应的DOM节点

componentWillUnmount()
组件在销毁时调用,可在这里执行清除定时器、断开socket等。
componentWillUnmount(){
   this.socket.close();
}

render()
render是一个React组件必不可少的函数,用于将模板转为 HTML 语言,并插入指定的 DOM 节点(不要在渲染时修改state)。可以返回null来表示不需要渲染任何东西,也可以根据不同的情况渲染不同的模板或者组件。

 render() {
   const { errors } = this.state;
   //const { errors } = this.state;
   if(errors){
       return (<ErrorPage />);
  }
  return (<TextField />)
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值