星期三, 10月 05, 2016

React Component shouldComponentUpdate 實作


最近朋友遇到一個有趣的React問題,可能頁面上有個值,一秒鐘會有幾萬筆資料進來,但是如果要一直更新畫面,效果不好。

這邊我推薦使用shouldComponentUpdate 來阻擋這種一秒鐘幾十萬資料變動的畫面呈現議題。

範例程式碼如下
http://jsbin.com/lilubaj

1. ParentComponent每1ms變動一次數值給ChildComponent(this.state.count)。
2. ChildComponent會在畫面上呈現(this.props.count)。
3. shouldComponentUpdate 有個timer設置每1秒才會允許畫面更新一次。
4. componentWillReceiveProps 原本的資料還是每1ms都會更新(資料流是正確的)。