分析React fiber

React fiber

是最新react用的算法選擇,其大概的介紹點擊這裏;react

如今的侷限

在現有React中,更新過程當中是同步的(這個js代碼的代碼執行相關)git

  • 同步的
  • 遞歸的
  • 渲染和調和

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.github

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.redux

fiber 實現方式

破解JavaScript中同步操做時間過長的方法其實很簡單——分片。 數據結構

React Fiber把更新過程碎片化,每執行完一個更新過程,將控制權交給react,它會根據優先級安排下一次的任務; dom

維護每個分片的數據結構,就是Fiber。異步

參考文件函數

影響

在現有的React中,每一個生命週期函數在一個加載或者更新過程當中絕對只會被調用一次;在React Fiber中,再也不是這樣了,第一階段中的生命週期函數在一次加載和更新過程當中可能會被屢次調用!ui

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

相關文章
相關標籤/搜索