React16.3.0以后的生命周期(一) - 组件加载

组件加载

当组件被实例化并且插入Dom时所执行的方法,也会按照下的顺序依次执行。

  • constructor()

    构造方法。

    这个方法有两个目的:

    • 初始化一个本地state

      this.state = {color: 'red'};
      要避免将 props参数直接赋值给 state, this.state = {color: props.color}是不允许 的
    • 绑定方法。

      我们知道React Class中是不会继承this的,如果在class的方法中使用this,那么我们需要将this绑定到方法中。

      this.clickHandler = this.clickHandler.bind(this);
      绑定 this,将需要 super(props),否则会提示找不到 this.

      示例:

      constructor(props) {
        super(props);
        this.state = {color: 'red'};
        this.clickHandler = this.clickHandler.bind(this);
      }
  • static getDerivedStateFromProps()

    当本地state需要根据props来改变的时候可调用此方法。

    这个方法是在render()前会被执行,只要执行render()都会被在之前被触发。

    该方法有两个参数propsstate; 返回值为state对象, 不需要返回整体state,把需要改变的state返回即可。

    示例:

    static getDerivedStateFromProps(props, state) {
      if(props.color !== state.color) {
        return {color: props.color};
      }
    }
  • render()

    这个方法是React组件中必须要提供的方法。当state或者props任一数据有更新时都会执行。

    需要注意当继承 PureComponent时,不会对对象进行深度比较,也就是,不会根据对象内的对象变化时执行 render().

    render()是一个纯函数,也就是不能在这个方法中有类似setState()这样的行为。

    返回的数据类型可以有:

    • nullStringNumberArrayBoolean
    • React elements
    • Fragment
    • Portal
    注意:不能返回 undefined.

shouldComponentUpdate()返回false时,无论stateprops有没有变化,这个方法都不执行。

示例:

render() {
  return (
    <div>{this.state.color}</div>
  );
}
  • componentDidMount()

    componentDidMount()方法是在组件加载完后立即执行,也就是当该组件相关的dom节点插入到dom树中时。该方法在组件生命中只执行一次。

    一般情况,我们会在这里setState()根据props的值,也可以从这里调用接口,获取服务端的数据,也可以在这里监听websocket、setInterval等操作。

    注意:一些监听需要在组件卸载时清理掉,否则会引起异常。

    示例:

    componentDidMount() {
      this.setState({color: this.props.color});
    }

    在线示例

推荐阅读《React 手稿》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值