react的生命周期

一个react组件在浏览器中存在三种状态:1(组件挂载)Mounting 2(组件更新)Updating 3(组件卸载)Unmounting


react的生命周期_第1张图片

每个状态下有它自己的声明周期函数:

(组件挂载)Mounting

组件挂载就是组件实例从被创建到插入DOM中的过程,是组件初次渲染的过程,会依次执行下面函数:

  1. constructor(props, context) --构造函数,在组件被创建时候调用 一次
  2. componentWillMount() --在组件被渲染之前(render()方法被调用之前)调用。所以在此函数中进行setstate不会导致组件重复渲染。componentWillMount() 是唯一一个在服务器端渲染调用的生命周期钩子,不过一般建议用 constructor()
  3. render() --react组件中必不可少的核心函数,切记不可以在此函数中使用setState修改 state,因为每次setState改变state都会重新渲染组件;否则会造成死循环。
  4. componentDidMount() --在组件挂载之后立即执行,适用于一些如:需要初始化DOM节点的操作或者AJAX请求等。在该钩子函数中进行setState()操作会导致组件重新渲染。组件内部可以通过ReactDOM.findDOMNode(this)来获取当前组件的节点,然后就可以像Web开发中那样操作里面的DOM元素了

(组件更新)Updating

propsstate中的任意一项发生改变,或者调用this.forceUpdate时,都会导致组件更新和重新渲染。组件更新时,调用以下函数:

  • componentWillReceiveProps(nextProps)--一个已挂载的组件接收到新的props之前调用。
    如果需要更新状态以响应prop更改(例如,重置它),则可以比较this.propsnextProps,并在此方法中使用this.setState执行状态转换。mounting状态不会调用此方法,调用this.setState不会触发此方法。
  • shouldComponentUpdate(nextProps, nextState) --当组件接收到新的props或者state时,要进行rendering之前会调用。该钩子函数用于告诉React组件是否需要重新渲染, 其默认返回true 。目前,如果shouldComponentUpdate()返回false,则不会调用componentWillUpdate()render()componentDidUpdate()。 请注意,将来React可能会将shouldComponentUpdate()作为提示而不是严格指令,并且返回false仍可能导致组件的重新呈现。
  • componentWillUpdate(nextProps, nextState) --shouldComponentUpdate()返回true或者调用forceUpdate()之后或者props有改变,该钩子函数会被调用。不能在这里调用setState,如果需要设置 state,应该在componentWillReceiveProps()中调用setState()。初始化组件时不执行此方法。
  • render() --
  • componentDidUpdate()--组件更新之后调用此方法,在此方法中可以操作DOM。

(组件卸载)Unmounting

组件从DOM中移除时,调用一下方法:

  • componentWillUnmount()--在组件卸载和销毁前调用, ReactDOM.unmountComponentAtNode()可以触发此方法。在此方法中做一些清理事情,一般在componentDidMount()中注册的事件都需要取消,比如:取消定时器,取消网络请求,解绑DOM事件。

注意:

  1. react的所有生命周期函数中当且仅有 render() 函数是必须的,其他生生命周期函数都是非必需的。
  2. setState() 通常在 componentWillMount() componentDidMount() componentWillReceiveProps() 以及 componentDidUpdate() 这几个生命周期钩子函数中调用;componentWillUpdate()render() 这两个生命周期函数中严禁调用 setState()

你可能感兴趣的:(react的生命周期)