react生命周期
constructor(props)
在创建组件实例的时候调用一次。
componentWillMount()
It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering.
render:
The render() function should be pure, meaning that it does not modify component state. Render is only used for displaying content, we put the code that should handle things like Ajax requests in what React calls lifecycle events.
不能调用setState方法,会导致死循环。
componentDidMount:
Invoked immediately after the component is inserted in the DOM.If we fetch external data from an API, we’ll put it in this lifecycle event.挂载到DOM树后触发,在这里可以用refs访问组件对应的DOM节点。
Setting state in this method will trigger a re-rendering.
componentWillReceiveProps()
invoked before a mounted component receives new props,and react doesn't call this method with initial props during mounting.
React may call this method even if the props have not changed,so you need to compare this.props and nextProps, and perform state transitions using this.setState() in this method.
shouldComponentUpdate(nextProps, nextState)
默认返回true.
对于大型组件,如果nextProps/nextState没有变化,可以return false to skip the whole rendering process, including calling render() on this component and below,以提高应用性能。
componentWillUpdate(prevProps, prevState)
componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.
componentDidUpdate(prevProps, prevState)
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props.
componentWillUnmount()
Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in componentDidMount.
forceUpdate()
If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child.
如果Clock组件的key变化,上述代码每秒都会重新执行从constructor到componenDidMount的方法,还包括ComponentWillUnmount()方法。
如果Clock组件无key属性或固定,则react会复用Clock组件,mouting过程中的方法只会执行一遍,之后每秒会执行componetWillUpdate()及相关方法一次。
同理对于单页应用,页面跳转出去再回来,mounting期间的方法不会再执行。若在同一位置的Dom被替换或移除了,则重新初始化并执行mouting期间的钩子函数。
嵌套组件时,父组件会先运行到render方法,再执行子组件的钩子函数到DidMount/DidUpdate方法,最后父组件触发DidMount/DidUpdate方法。
父组件因为setState/props导致render时,父组件会依次调用生命周期图中的对应方法。因为子组件在父组件的render方法中,所以其嵌套的所有的子组件也会执行相应的生命周期函数,而不论子组件的state/props有无变化。