美文网首页
react生命周期

react生命周期

作者: 黎明的叶子 | 来源:发表于2021-12-06 18:54 被阅读0次
    react生命周期图

    装载过程(Mount )

    组件第一次在 DOM 树中渲染的过程
    1.constructor:初始化 state

    constructor (props) {
        super(props)
        this.state = { 
        }
      }
    

    2.componentWillMount
    是紧贴 render 函数之前被调用,可以写同步初始化数据,初始化页面大小的方法。异步请求不写在这里。建议写在DidMount里面(具体为啥,不清楚)

    componentWillMount () {
        this.setState({
          xxx: this.props.defaultxxx
        })
      }
    

    3.render
    一定要实现,本身并不往 DOM 树上渲染或者装载内容,它只是返回一个 JSX 描述的结构,最终由 React 来操作渲染过程,React 库肯定是要把所有组件返回的结果综合起来,才能知道该如何产生对应的 DOM 修改。

    render() { 
          let { } = this.props 
          return <div>
             <h1>{}</h1>
             <button onClick={this.add}>+</button> 
          </div> 
       }
    

    4.componentDidMount
    render 函数被调用完之后, componentDidMount 函数并不是会被立刻调用,componentDidMount 被调用的时候, render 函数返回的东西已经引发了渲染,组件已经被“装载”到了 DOM 树上。这里用来加载外部数据用的。(异步数据可以在这里)调用this.setState会触发render再次执行。

    更新过程(Update )

    当 props 或者 state 被修改、组件被重新渲染的时候,就会引发组件的更新过程

    1. componentWillReceiveProps
      this.setState 方法触发的更新过程不会调用这个函数

      父组件的 render 函数被调用,在 render 函数里面被渲染的子组件就会经历更新过程,不管父组件传给子组件的 props 有没有改变,都会触发子组件的componentWillReceiveProps 函数

      这个函数适合根据新的 props 值(也就是参数 nextProps )来计算出是不是要更新内部状态 state

      把传入参数 nextProps this.props 作对比, nextProps代表的是这次渲染传入的 props 值, this.props 代表的上一次渲染时的 props 值,只有两者有变化的时候才有必要调用 this.setState 更新内部状态

     componentWillReceiveProps (nextProps) {
        if (nextProps.defaultPageSize !== this.props.defaultPageSize) {
          this.setState({
            pageSize: nextProps.defaultPageSize
          })
        }
      }
    
    1. shouldComponentUpdate
      它决定了一个组件什么时候不需要渲染

      例如某个组件 支持两个 props,caption 和 initValue,initValue 只用于初始化数值,只有caption 变时才需要更新

    // return false 和 什么也不返回 则都不更新此组件。
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.caption !== this.props.caption 
    }
    
    1. componentWillUpdate
    2. render
    3. componentDidUpdate

    卸载过程(Unmount )

    组件从 DOM 中删除的过程

    1. componentWillUnmount
      合做一些清理性的工作

    相关文章

      网友评论

          本文标题:react生命周期

          本文链接:https://www.haomeiwen.com/subject/owpwjltx.html