【REACT NATIVE 系列教程之四】重新整理元件RENDER(重新渲染)的三種方式詳解
開發過遊戲的都應該很清楚,“刷屏”是多麼的重要。其實開發應用也如此,當元件的資料被修改後,如何及時更新元件呈現出最新的資料與效果一樣至關重要。
那麼這裡Himi大概講三種常用的方式:
- this.setState() 【最為常用】
這是在事件處理函式中和請求回撥函式中觸發 UI 更新的主要方法。
一般情況下setState() 總是觸發一次重繪,除非在 shouldComponentUpdate() 中實現了條件渲染邏輯。如果使用可變的物件,但是又不能在 shouldComponentUpdate() 中實現這種邏輯,僅在新 state 和之前的 state 存在差異的時候呼叫 setState() 可以避免不必要的重新渲染。
舉例、程式碼段如下:
1234567891011121314151617181920212223242526 | constructor(props){super(props);this.state={myName:'I am MyName!',};}testFun(){this.setState({myName:'元件被重新整理了'});}render(){......<TouchableHighlight underlayColor='#4169e1'onPress={this.testFun.bind(this)}><Imagesource={require('./res/himi.png' |
1. 在this.state中添加了一個 字串變數 myName 用於Text 元件的文字顯示
2. 自定義了一個 testFun 函式,用於 Touchable的回撥處理,其中呼叫了this.setState 函式並修改了myName的資料
3. 在render中添加了一個高亮觸控元件,用於演示效果。
【注】假如有 a、b、c三個元件,b 是 a 的子元件,c是 b 的子元件,那麼 b 中 setState 之後,b 和 c 會 rerender,而 a 不會。 因此建議大家可以把每個元件提供一個重繪介面,然後提供給其他元件呼叫。
效果如下:(點選檢視動態效果)
2. this.forceUpdate() 【較為常用,但是不推薦】
如果 render() 方法從 this.props 或者 this.state 之外的地方讀取資料,你需要通過呼叫 forceUpdate() 告訴 React 什麼時候需要再次執行 render()。如果直接改變了 this.state,也需要呼叫 forceUpdate()。
呼叫 forceUpdate() 將會導致 render() 方法在相應的元件上被呼叫,並且子級元件也會呼叫自己的 render(),但是如果標記改變了,那麼 React 僅會更新 DOM。通常情況下,應該儘量避免所有使用 forceUpdate() 的情況,在 render() 中僅從 this.props 和 this.state 中讀取資料。這會使應用大大簡化,並且更加高效。
舉例、在上面的示例程式碼基礎上修改,如下:
123456789101112131415161718192021222324252627282930 | testFun(){this.state.myName='元件被重新整理了';}testForceFun(){this.forceUpdate();}render(){......<TouchableHighlight underlayColor='#4169e1'onPress={this.testFun.bind(this)}><Image source={require('./res/himi.png')}style={{width:70,height:70}}/></TouchableHighlight><TouchableHighlight underlayColor='#4169e1'onPress={this.testForceFun.bind(this)}><Image source={require('./res/himi.png')}style={{width:40,height:40}}/></TouchableHighlight>......} |
改動說明:
a) 修改 testFun 函式,讓其作用只是修改了 myName 的值,並