react 生命周期

TB1Ng7_MpXXXXamXFXXXXXXXXXX-2850-2945.jpg

componentWillMount 挂载组件
constructor 开始渲染
componentDidMount 挂载完成

componentWillReceiveProps 接收了新的属性
componentWillUpdate 要重新渲染了
componentDidUpdate 更新渲染完成了
componentWillUnmount 组件销毁

render 渲染

class Person extends React.Component {

  // 即将出生(刚开始调用)
  componentWillMount() {
    console.log('我要出生了,我的名字叫 ', this.props.name);
  }

  // 出生(开始渲染,准备初始数据,调用 render 方法)
  constructor(props) {
    super(props);

    console.log('name', this.props.name);

    this.state = {
      name: this.props.name,
      age: 0
    };

    // 时间开始转动,5 秒等于 1 岁
    this.timer = setInterval(() => {
      this.setState({
        age: this.state.age + 1
      });
    }, 5000);

    console.log('我正在出生');
  }


  // 出生完毕(调用 render 完成并渲染到页面上)
  componentDidMount() {
    console.log('我已经出生');
  }

  // 接收了新的属性
  componentWillReceiveProps(nextProps) {
    // 换了个新名字,固定的属性
    if (nextProps.name !== this.state.name) {
      console.log('我换了个名字:', nextProps.name);
      this.setState({
        name: nextProps.name
      });
    }
  }

  // 要重新渲染了(准备过生日)
  componentWillUpdate() {
    console.log('我要改变了!');
  }
  // 更新渲染完成了(过完生日)
  componentDidUpdate() {
    console.log('我改变完了!');
  }

  // 要火化了(组件销毁)
  componentWillUnmount() {
    // 停止时间
    console.log('再见啦!');
    clearInterval(this.timer);
  }

  render() {
    console.log('我正在改变!');
    return (
      <div>
        <h1>姓名:{this.state.name},年龄:{this.state.age}</h1>
      </div>
    );
  }
}

标签: 无

发表评论: