react的生命周期 一、新生命周期1、挂载阶段1.1 constructor(1)在React组件挂载之前被调用(2) 初始化函数内部 state或者在this上挂载方法 1.2 getDerivedStateFromProps(1)为静态方法,不能访问到组件实例this(2)在创建或更新阶段调用或者在props、state和render方法前调用(3)返回一个对象来更新 state, 如果返回 null 则不更新任何内容 1.3 render(1)用于渲染DOM结构(2)不要在 render 里面 setState, 否则会触发死循环导致内存崩溃 1.4 componentDidMount(1) 挂载到真实DOM节点后执行,render方法之后执行(2)是发送网络请求、启用事件监听方法的好时机 2、更新阶段1.1 getDerivedStateFromProps(1) 在创建或更新阶段调用或者在props、state和render方法前调用 1.2 shouldComponentUpdate(1)在组件更新之前调用,可以控制组件是否进行更新, 返回true时组件更新, 返回false则不更新(2)不要 shouldComponentUpdate 中调用 setState(),否则会导致无限循环调用更新、渲染,直至浏览器内存崩溃 1.3 render1.4 getSnapshotBeforeUpdate(1) render后执行,获取组件更新前的信息,即将对组件进行挂载时调用。 1.5 componentDidUpdate(1)组件更新结束后触发。首次渲染不会执行 3、卸载阶段1.1 componentWillUnmount(1)组件卸载前调用(2)此生命周期是取消网络请求、移除监听事件、清理 DOM 元素、清理定时器等操作的好时机 二、 旧生命周期1、挂载阶段constructorcomponentWillMount(废弃)rendercomponentDidMount 2、更新阶段componentWillReceiveProps(废弃)shouldComponentUpdatecomponentWillUpdate(废弃)rendercomponentDidUpdate 3、卸载阶段componentWillUnmount 一、新生命周期 1、挂载阶段 1.1 constructor (1)在React组件挂载之前被调用 (2) 初始化函数内部 state或者在this上挂载方法 1.2 getDerivedStateFromProps (1)为静态方法,不能访问到组件实例this (2)在创建或更新阶段调用或者在props、state和render方法前调用 (3)返回一个对象来更新 state, 如果返回 null 则不更新任何内容 1.3 render (1)用于渲染DOM结构 (2)不要在 render 里面 setState, 否则会触发死循环导致内存崩溃 1.4 componentDidMount (1) 挂载到真实DOM节点后执行,render方法之后执行 (2)是发送网络请求、启用事件监听方法的好时机 2、更新阶段 1.1 getDerivedStateFromProps (1) 在创建或更新阶段调用或者在props、state和render方法前调用 1.2 shouldComponentUpdate (1)在组件更新之前调用,可以控制组件是否进行更新, 返回true时组件更新, 返回false则不更新 (2)不要 shouldComponentUpdate 中调用 setState(),否则会导致无限循环调用更新、渲染,直至浏览器内存崩溃 1.3 render 1.4 getSnapshotBeforeUpdate (1) render后执行,获取组件更新前的信息,即将对组件进行挂载时调用。 1.5 componentDidUpdate (1)组件更新结束后触发。首次渲染不会执行 3、卸载阶段 1.1 componentWillUnmount (1)组件卸载前调用 (2)此生命周期是取消网络请求、移除监听事件、清理 DOM 元素、清理定时器等操作的好时机 二、 旧生命周期 1、挂载阶段 constructor componentWillMount(废弃) render componentDidMount 2、更新阶段 componentWillReceiveProps(废弃) shouldComponentUpdate componentWillUpdate(废弃) render componentDidUpdate 3、卸载阶段 componentWillUnmount