react 组件的生命周期样例

import React, { Component } from 'react';

export default class Main extends Component {
 //构造函数
  constructor(props) {
    super(props);
    console.log("constructor");
    //初始化状态值
    this.state = {message: "helloworld"}
  }
 
  //准备加载组件
  componentWillMount() {
    console.log("componentWillMount");
  }
 
  //渲染界面
  render() {
    console.log("render");
    return (
      <div style={styles.container}>
        <p style={styles.info}>
          {this.state.message}
        </p>
      </div>
    );
  }
 
  //组件加载成功并渲染出来
  componentDidMount() {
    console.log("componentDidMount");
  }
 
  //组件接收到新的 props 时触发
  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps");
  }
 
  //决定是否需要更新组件
  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate");
  }
 
  //组件重新渲染前会调用
  componentWillUpdate(nextProps, nextState) {
    console.log("componentWillUpdate");
  }
 
  //组件重新渲染后会调用
  componentDidUpdate(prevProps, prevState) {
    console.log("componentDidUpdate");
  }
 
  //组件被卸载前会调用
  componentWillUnmount() {
    console.log("componentWillUnmount");
  }
}
 
const styles = StyleSheet.create({
  container:{
     flex:1,
     marginTop:40,
     alignItems:'center',
  },
  info:{
    fontSize:20,
  },
});
 
AppRegistry.registerComponent('HelloWorld', () => Main);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容