移动测试开发 前端 react 生命周期探索

opentest-oper@360.cn · 2019年04月08日 · 504 次阅读

在具有许多组件的项目中,在销毁时释放组件所占用的资源非常重要,
在 react 中每一个组件 Component 都有自己独立的状态,互相不受影响
在浏览器中的状态有三种:Mounting(挂载)、Update(更新)、Unmounted(卸载)

graph LR
A(state or props changed) -.-> B(diff)
B -.-> C(render)
C -.->D(update)
D --> A
D --> E(Unmounted)
F(Mounted)-->D
  1. 挂载 constructor
  2. 初始化方法定义 componentWillMount
  3. 第一次渲染 (render) 前被加载一次,它也是一个放置初始化 state 值的好地方。 render componentDidMount
  4. render 阶段触发一次,ajax 调用可以放到这里
  5. 每次渲染之后执行,获取 dom 的好地方,也可以 setState,但是会额外触发一次 render
  6. 更新 componentWillReceiveProps(nextProps)
  7. 这个生命周期涉及到父子组件传参的问题,组件正在接收新的 props 时,它将被调用。但是它不会在初次页面渲染(render)时被调用 shouldComponentUpdate(nextProps, nextState)
  8. 这个生命周期是用来做组件优化的,它返回的是布尔值,默认返回 true。当一个新的 props 或者 state 正在被接收时,该钩子会在页面渲染(render)前被调用。它也不会在初次页面渲染(render)时被调用。
  9. 组件接受新的 state 或者 props 时调用,我们可以设置在此对比前后两个 props 和 state 是否相同,如果相同则返回 false 阻止更新,因为相同的属性状态一定会生成相同的 dom 树,这样就不需要创造新的 dom 树和旧的 dom 树进行 diff 算法对比,节省大量性能,尤其是在 dom 结构复杂的时候
  10. 如返回 false,将不会触发 componentWillUpdate(), render(), componentDidUpdate()。 componentWillUpdate
  11. 该钩子在 shouldComponentUpdate() 钩子之后(返回 true),render() 之前调用
  12. 不会在初次页面渲染(render)时被调用。该钩子的作用是为更新做准备。 render componentDidUpdate
  13. 如果在这里 setState,应设置前置条件,否则会陷入无限循环 (深有体会)
  14. 组件更新之后调用立即刷新 DOM
  15. 不会在初次页面渲染(render)时被调用。
  16. 卸载 componentWillUnmount
  17. 组件销毁之前调用
  18. 一般用于清除定时器,卸载 dom 事件避免内存泄漏和一些无意义的操作
class SinglePlayer extends React.Component {
//父组件没有传值,定义一个默认的
static defaultProps = {
app: 'weishi',
siz: 100
}
constructor(){
super()
this.state={}
}
//渲染函数
render(){
return (
<div className="opentest">opentest</div>
)
}
componentWillMount(){}//即将渲染
componentDidMount(){}//组件渲染完成
componentWillReceiveProps(nextProps){}//props值更新调用
shouldComponentUpdate(nextProps,nextState){//组件优化
//对比前后props和state
if ( nextProps.data == this.props.data ) {
return false;
}
return true;
}
componentWillUpdate(){}//组件更新之前
componentDidUpdate(){}//组件更新之后
componentWillUnmount(){}//组件即将销毁
}

总结:
react 钩子函数执行顺序

graph TD
subgraph .
A(constructor 初始化state和props) -.即将渲染.-> B(componentWillMount)
B -.渲染更新.-> C(render)
C -.dom更新之后的操作.->D(componentDidMount)
end
subgraph .
D -.没接收到新的props.->F(shouldComponentUpdate)
D -.接收新的props.->E(componentWillReceiveProps)
E -.组件优化,返回boolean值.->F
F -.true 组件即将更新.->G(componentWillUpdate)
F -.false.->J(componentWillUnmount)
G -.更新.-> H(render)
H -.组件更新之后.-> I(componentDidUpdate)
end
I -.组件卸载.-> J(componentWillUnmount)

熟悉 react 生命周期流程,开发 react 应用渲染页面会更加的得心应手
参考文章

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册