用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
[TOC] ## 前言 通过本文你将知道react的基本生命周期,并对各个周期适合写什么函数做什么事情有更深度的了解。 ## 图解生命周期 ![图解生命周期](https://box.kancloud.cn/cc810c68d39d688c26addf852c8af87d_617x294.png) ## 生命周期的状态 - 组件的生命周期分成三个状态:已渲染,更新渲染,被移出 > Mounting:已插入真实 DOM > Updating:正在被重新渲染 > Unmounting:已移出真实 DOM - 钩子函数 React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。 ~~~ componentWillMount() componentDidMount() componentWillUpdate(object nextProps, object nextState) componentDidUpdate(object prevProps, object prevState) componentWillUnmount() ~~~ 此外,React 还提供两种特殊状态的处理函数 ~~~ componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用 shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用 ~~~ ## 生命周期的探索 经过探索可以得到组件的生命周期在不同状态的执行顺序: - 当首次装载组件时,按顺序执行 getDefaultProps、getInitialState、componentWillMount、render 和 componentDidMount - 当卸载组件时,执行 componentWillUnmount; - 当重新装载组件时,此时按顺序执行 getInitialState、componentWillMount、render 和 componentDidMount,但并不执行 getDefaultProps - 当再次渲染组件时,组件接受到更新状态,此时按顺序执行 componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render 和 componentDidUpdate ## 一些个人建议 ### 初始化数据可以在componentWillMount 此时执行不会触发重新渲染 ### 拉取数据在componentDidMount 执行 下面这段代码的好处在于将整个组件需要的loading,data,error统一放到状态机去管理,在请求数据渲染的时候去执行相关的状态判断,在组件完成渲染的时候,请求数据之后更新状态机然后完成新数据的展示。 ~~~ getInitialState: function() { return { data: null, fetching: false, error: null }; }, render: function() { if (this.props.fetching) { return <div>Loading...</div>; } if (this.props.error) { return ( <div className='error'> {this.state.error.message} </div> ); } return <Counter {...data} /> }, componentDidMount: function() { this.setState({fetching: true}); Axios.get(this.props.url).then(function(res) { this.setState({data: res.data, fetching: false}); }).catch(function(res) { this.setState({error: res.data, fetching: false}); }); } ~~~ - componentWillReceiveProps() 这个方法允许我们在state改变触发组件渲染之前,对数值做响应的修改。需要注意的是,这个事件是针对整个组件的,所以你要触发改变首先要想好有哪些属性可能发生改变,需要做修改的是那些。需要做的是针对组件整体执行的事件而不针对某一个state,所以传入的是整体的props。 ~~~ componentWillReceiveProps: function(newProps) { this.setState({count: newProps.initialCount}); }, ~~~ - shouldComponentUpdate() 方法允许我们自行决定下一个state更新时是否触发重复render。此方法返回一个布尔值,且默认是true。但是我们也可以返回false,这样下面的(生命周期)方法将不会被调用:这个方法可以用来避免一些用户交互过多的引起状态更新,导致性能降低。 ~~~ shouldComponentUpdate: function(nextProps, nextState) { if (this.props.text === nextProps.text) return false; return true; }, ~~~ - componentWillUpdate() 当接收到新的属性或者state时在render之前会立刻调用componentWillUpdate()方法。可以利用此时机来为更新做一些准备工作,虽然这个阶段不能调用this.setState()方法,但是可以进行一些前置工作。 - componentDidUpdate() 可以在这个方法里写一些公共的组件更新后的后置事件。这种最常见的是引入一些第三方库之后才可以进行的操作。 - componentWillUnmount() 这个阶段主要是需要清除一些无用的dom对象,一些计时器等,避免消耗 ## 参考资料 - [react生命周期详解](https://zhuanlan.zhihu.com/purerender/20312691) -