挂载阶段html
constructor
构造函数react
componetWillMount
组件初始化渲染前调用web
render
组件渲染面试
componentDidMount
组件挂载到DOM
后调用浏览器
更新阶段网络
componentWillReceiveProps
组件将要接收新props
前调用shouldComponentUpdate
组件是否须要更新componentWillUpdate
组件更新前调用render
组件渲染componentDidUpdate
组件更新后调用卸载阶段异步
componentWillUnmount
组件卸载前调用挂载阶段函数
constructor
构造函数,若是不初始化 state 或不进行方法绑定,则不须要为 React 组件实现构造函数。性能
static getDerivedStateFromProps(props, state)
会在调用 render 方法以前调用,而且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,若是返回 null 则不更新任何内容。code
render
componentDidMount
组件挂载到DOM
后调用。在这里能够直接调用 setState()
。它将触发额外渲染,但此渲染会发生在浏览器更新屏幕以前。从而保证了即便在render()
两次调用的状况下,用户也不会看到中间状态。但它会致使性能问题,因此要谨慎使用。
更新
static getDerivedStateFromProps
shouldComponentUpdate
render
getSnapShotBeforeUpdate
在最近一次渲染输出(提交到 DOM 节点)以前调用。它使组件能在发生更改以前从 DOM 捕获一些信息(例如,滚动位置)。它的任何返回值将做为参数传递给componentDidUpdate
。componentDidUpdate
组件更新后调用,首次渲染不会执行此方法。在这里直接调用setState()
时,必须将setState()
包裹在一个条件语句里,不然会致使死循环。它还会致使额外的从新渲染,虽然用户不可见,但会影响组件性能。卸载
componentWillUnmount
这里不该调用setState()
,由于组件不会从新渲染。错误处理
static getDerivedStateFromError
在后代组件抛出错误后被调用,将抛出的错误做为参数,并返回一个值以更新 state。componentDidCatch
componentWillMount
、componentWillReceivepPops
和componentWillUpdate
?componentWillMount
:异步渲染机制可能会致使单个组件实例能够屡次调用该方法。不少开发着目前会将事件绑定、异步请求等写在componentWillMount
中,一旦异步渲染时componentWillMount
被屡次调用,将会致使:
componentWillMount
会被调用,可是会因忽略异步获取的数据致使 IO 资源被浪费。componentWillUpdate
的场景是配合componentDidUpdate
,分别获取 rerender 先后的视图状态,进行必要的处理。但随着 suspense、time slicing、异步渲染等机制的到来,render 过程能够被分割成屡次完成,还能够被暂停甚至回溯,这致使**componentWillUpdate
和componentDidUpdate
执行先后可能会间隔很长时间**,足够使用户进行交互操做更改当前组件的状态,这样可能会致使难以追踪的 bug。参考: