React 生命周期渲染问题点
渲染分为两个阶段: reconciliation和commit。前者过程是可以打断的,后者是不能暂停,会一直更新界面直到完成。
Reconciliation阶段包括
- componentWillMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
Commit 节点包括
- componentDidMount
- componentDidUpdate
- componentWillUnmount
因为Reconciliation节点是可以被打断的,所以Reconciliation节点会执行的生命周期函数就有可能会出现多次调用的情况,从而可能引发Bug,Reconciliation阶段会调用的几个函数除了shouldComponentUpdate以外的函数都应该避免使用。
V16中引入了新的API来解决这个问题getDerivedStateFromProps用于替换componentWillReceiveProps,该函数会在初始化和update时被调用。getSnapshotBeforeUpdate用于替换componentWillUpdate该函数会在update后DOM更新前被调用,用于读取最新的DOM数据。