美文网首页程序员
React 16.3.0生命周期

React 16.3.0生命周期

作者: 前端小兵 | 来源:发表于2018-07-06 10:58 被阅读35次

组件的生命周期可分成三个状态

  • 挂载:组件被实例化并挂载在到dom树这一过程称为挂载
  • 更新:当组件的属性或者状态改变时会重新渲染
  • 卸载:当一个组件被移出Dom树时,组件就会被卸载

挂载

image
  • 首次渲染执行的顺序如图上
    • getDefaultProps相当于ES6中staticdefaultProps = {}
    • getInitialState相当于constructor中的 this.state = {}
  • componentWillMount()
    • render()之前调用被调用,因此在这方法里设置this.setState是不会触发不会触发重渲
    • 这是唯一会在服务端渲染调起的生命周期钩子函数,在服务端渲染的场景中可以在这发送AJAX请求
  • componentDidMount()
    • 该方法在组件挂载完成后立即调用,并且只会调用一次
    • 通常在这个方法中发送AJAX请求

更新

Props改变

image

State改变

image
  • componentWillReceiveProps
    • 方法在已挂载的组件接收到新属性前调用
    • 要合理使用componentWillReceiveProps需做好条件判断
    componentWillReceiveProps(nextProps) {
        if(nextProps.myProp !== this.props.myProps) {
            // nextProps.myProp has a different value than our current prop
        }
    }
    
  • shouldComponentUpdate
  • componentWillUpdate
  • componentDidUpdate

卸载

image
  • componentWillUnmount
    • 当组件被卸载之前立刻调用;可以在该方法里处理任何必要的清理工作,例如解绑定时器,取消网络请求,清理任何在componentDidMount环节创建的DOM元素。

错误处理

  • componentDidCatch()
    • 在渲染过程中发生错误时会被调用;只可以处理子组件中产生的、未处理的错误,能够捕获的错误类型有子组件render函数中产生的错误及生命周期函数中产生的非异步错误
    //父组件或祖宗组件中实现
    componentDidCatch(errorString, errorInfo) {
        this.setState({
            error: errorString
        });
        ErrorLoggingTool.log(errorInfo);
    }
    render() {
        if(this.state.error) return <ShowErrorMessage error={this.state.error} />
        return (
            // render normal component output
        );
    }
    

相关文章

网友评论

    本文标题:React 16.3.0生命周期

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