React笔记 (七)React生命周期的概念和使用

148 阅读1分钟

生命周期的概念

生命周期函数是指在某一时刻,组件会自动调用执行的函数 如:render

挂载(Mounting)阶段

componentWillMount

在组件挂载到DOM前调用,且只会被调用一次,在这边调用this.setState不会引起组件重新渲染,也可以把写在这边的内容提前到constructor()中,所以项目中很少用。

componentWillMount() {
}

render

根据组件的props和state(无两者的重传递和重赋值,论值是否有变化,都可以引起组件重新render)

render() {
}

componentDidMount

组件挂载到DOM后调用,且只会被调用一次
一般请求数据放在这里

componentDidMount() {
    // 组件被挂在到页面上时自动执行
}

更新(update)阶段

props发生变化时:componentWillReceiveProps=>componentDidMount=>componentWillUpdate=>render=>componentDidUpdate 执行setState时:componentDidMount=>componentWillUpdate=>render=>componentDidUpdate

componentWillReceiveProps

一个组件要从父组件接收参数 如果它之前已经存在于父组件才会执行

componentWillReceiveProps() {
}

componentDidMount

更像是一个问句,需要return一个布尔值,为false将不会刷新
componentDidMount接收两个参数,一个是props是否刷新新,一个是state是否刷新 可以用来做刷新显示,来提升性能

shouldComponentUpdate(nextProps, nextStates) { 
    // 应该使用这个方法,否则无论state是否有变化都将会导致组件重新渲染
    if(nextStates.someThings === this.state.someThings){
      return false
    }
}

componentWillUpdate

在组件被更新之前执行,组件即将要更新,但是还没有更新,前提是shouldComponentUpdatereturn的值为true。

componentWillUpdate() {
}

render

render() {
}

componentDidUpdate

在组件被更新完成之后执行

componentDidUpdate() {
}

卸载阶段

componentWillUnmount

在组件要被移除的前一瞬间

componentWillUnmount() {
}