轉載自【黑米GameDev街區】 原文鏈接: http://www.himigame.com/react-native/2242.html
開發過遊戲的都應該很清楚,“刷屏”是多麼的重要。其實開發應用也如此,當組件的數據被修改後,如何及時更新組件呈現出最新的數據與效果一樣至關重要。
那麼這裏Himi大概講三種常用的方式:
this.setState() 【最爲常用】
這是在事件處理函數中和請求回調函數中觸發 UI 更新的主要方法。
一般情況下setState() 總是觸發一次重繪,除非在 shouldComponentUpdate() 中實現了條件渲染邏輯。如果使用可變的對象,但是又不能在 shouldComponentUpdate() 中實現這種邏輯,僅在新 state 和之前的 state 存在差異的時候調用 setState() 可以避免不必要的重新渲染。
舉例、代碼段如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | constructor(props) { super(props); this.state = { myName:'I am MyName!', };
}
testFun(){ this.setState({myName:'組件被刷新了'}); }
render() { ...... <TouchableHighlight underlayColor='#4169e1' onPress={this.testFun.bind(this)} > <Image source={require('./res/himi.png')} style={{width: 70, height: 70}} /> </TouchableHighlight> ...... )} |
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 中讀取數據。這會使應用大大簡化,並且更加高效。
舉例、在上面的示例代碼基礎上修改,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 的值,並沒有setState!所以不重繪
b) 添加 testForceFun 函數,作用是調用強制重繪函數。
c) render中多加了一個按鈕,來觸發 testForceFun函數。
運行效果圖如下:(注意 testForceFun 函數對應的是圖片較小的那個哦~ )
通過示意圖可以知道,Himi 調用了 testFun、接着調用testForceFun ,才能看到刷新。
3. this.setProps() 【不常用】
同一個節點上再次調用 React.render()
來更新根組件是首選的方式,也可以調用 setProps()
來改變組件的屬性,觸發一次重新渲染。
但是!此方法僅在根組件上面調用。也就是說,僅在直接傳給 React.render() 的組件上可用,在它的子級組件上不可用。如果你傾向於在子組件上使用 setProps(),不要利用響應式更新,而是當子組件在 render() 中創建的時候傳入新的 prop 到子組件中。
說的通俗一點:父組件不能直接修改 prop屬性,只能父類在使用傳入的時候進行設置。