浅析react中的class组件及生命周期

208 阅读1分钟

class组件的两种创建方式

  1. ES5
import React from 'react'

const A = React.createClass({
    render(){
        return (
            <div> hello </div>
        )
    }
})
  1. ES6
import React from 'react'

class A extends React.Component {
    constructor(props){
        super(props)
    }
    render(){
        return (
            <div> hello </div>
        )
    }
}

raect 中的生命周期

raect中的生命周期是按照以下顺序执行的

  • constructor ——————— 初始化state/props
  • render——————————创建虚拟DOM
  • componentDidMount———组件挂载到页面上
  • shouldComponentUpadte——确定是否更新页面
  • componentDidUpdate————页面更新完成
  • componentWillUnmount——组件从页面及内存中移除

几个被弃用的钩子

  • componentWillMount
  • componentWillUpdate
  • componentWillReceiveProps

几个钩子的注意事项

  1. componentDidMount
  • 主要用来在页面被挂载后执行代码(一般这里的代码依赖DOM,例如获取页面宽高)

  • 官方推荐这里可以发送Ajax请求


2. componentDidUpdate
  • 此处执行setState可能会出现死循环
  • 此处也可以发送Ajax请求,数据数据更新

3. componentWillUnmount
  • 此处需要销毁页面中的监听/Ajax等