分析React fiber

React fiber

是最新react用的算法选择,其大概的介绍点击这里;

现在的局限

在现有React中,更新过程中是同步的(这个js代码的代码执行相关)

  • 同步的
  • 递归的
  • 渲染和调和

fiber 目的

  1. 中断进程,后面还可以回到进程(work)中;
  2. 为各个进程(work)分优先级;
  3. 可以再次使用之前完成的进程(work);
  4. 终止后面不再使用的进程(work);

In order to do any of this, we first need a way to break work down into units. In one sense, that’s what a fiber is. A fiber represents a unit of work.

That’s the purpose of React Fiber. Fiber is reimplementation of the stack, specialized for React components. You can think of a single fiber as a virtual stack frame.

In concrete terms, a fiber is a JavaScript object that contains information about a component, its input, and its output.

fiber 实现方式

破解JavaScript中同步操作时间过长的方法其实很简单——分片。

React Fiber把更新过程碎片化,每执行完一个更新过程,将控制权交给react,它会根据优先级安排下一次的任务;

维护每一个分片的数据结构,就是Fiber。

参考文件

影响

在现有的React中,每个生命周期函数在一个加载或者更新过程中绝对只会被调用一次;在React Fiber中,不再是这样了,第一阶段中的生命周期函数在一次加载和更新过程中可能会被多次调用!

Reconciliation Phase:
  • componentWillMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate

这些在react fiber中可能执行多次

Commit Phase:
  • componentDidMount
  • componentDidUpdate
  • componentWillUnMount

这些只能执行一次

好处:
  • 不会丢帧
  • 每一帧都分开事务
  • 事务完成时进行提交
  • 可以取消事务优先级
坏处:
  • 调试困难(react的堆栈信息本身就是反人类的)
  • 很难了解问题原因
  • 非及时更新
注意点:

fiber新的调度系统,setState都是异步的,所以:

错误的姿势

this.setState({
    a: this.state.a + this.props.b
});

正确的姿势

this.setState((a, b) => ({  
    a: prevState.a + props.b
}))
fiber 的进展:

http://isfiberreadyyet.com

欢迎来github上 start

    原文作者:kevinstory
    原文地址: https://segmentfault.com/a/1190000011795478
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞