前端生命周期设计思考

这两天在设计完善框架的生命周期,所以当我回头去看之前写过的iOSreact-native的代码时,我不禁产生了疑问,之前用的这么多的生命周期的函数,为什么是这样设计的?每个生命周期用来做什么比较合适?比如react-native中想要去请求接口,是在componentWillMount还是在componentDidMount中更合适的?为什么?查了一些资料,结合我的经验思考,遂有此文。

生命周期主要讲的就是前端页面从生成-渲染-更新-销毁等几个阶段的过程,框架一般会提供该过程的回调和可用参数,提供给用户使用。只有了解清楚生命周期中每个阶段做的事情和状态后,我们才能因地制宜,写出更优雅的代码。

下面我们来通过对比看下iOS和react中生命周期,看看生命周期究竟是怎么设计的,为什么不同的框架的生命周期不太一样呢

iOS

iOS的文档核心是将页面的状态分成四种,生命周期的不同阶段就是围绕这四种状态的变化:

  1. Appearing 正在绘制
  2. Appeared 已绘制
  3. Disappearing 正在销毁
  4. Disappeared 已销毁

状态变化如下图所示:

生命周期

iOS生命周期

1
2
3
4
5
6
7
8
9
ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work.
ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
ViewWillDisappear/DidDisappear - Same idea as ViewWillAppear/ViewDidAppear.
ViewDidUnload/ViewDidDispose - In Objective C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.

react 生命周期

react的文档中,是根据行为来分类生命周期的:

  1. 渲染相关
  2. 更新相关
  3. 销毁渲染相关
  4. 其他
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#Mouting
constructor()
static getDerivedStateFromProps()
componentWillMount() / UNSAFE_componentWillMount()
render()
componentDidMount()
#Updating
componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
static getDerivedStateFromProps()
shouldComponentUpdate()
componentWillUpdate() / UNSAFE_componentWillUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
#Unmounting
componentWillUnmount()
#Error Handling
componentDidCatch()

可以注意到,两个框架的生命周期设计是不同的,我认为这种不同更多是来源于设计思想的不同,react使用DOM和Virtual DOM,所以而DOM的刷新是根据props和state来驱动的,可以理解为数据驱动,所以过程中会多一个些props和state的相关函数。而iOS的渲染是偏向于编码控制每个地方的变化,所以生命周期主要关注页面的生成和销毁,而不太关心中间页面的更新(因为页面更新是代码主动控制的)。

比较完iOS和react,生命周期究竟该怎么设计,重点就是根据你的框架的设计方案,把影响到你页面刷新的步骤提炼出来,设计成不同周期,最终目的地是让你的框架更好用,使用方能更好地理解你的框架,从而写出更优雅的代码。

参考文章