2017-09-08 132 views
2

我有下面的構造陣營本地:動態內容 - 渲染功能不更新視圖

constructor(props){ 
    super(props); 
    this.renderConversations = this.renderConversations.bind(this); 
    this.startConversation = this.startConversation.bind(this); 
    this.state = { 
     conversationArray: [] 
    } 

在功能startConversation我更新狀態變量。

startConversation(conversationObject) { 
    let currentResponse = conversationObject["responses"]; 
    let thisResponse = currentResponse[Math.floor(Math.random() * currentResponse.length)]; 

    this.state.conversationArray.push(thisResponse); 
    this.renderConversations(); 

    } 

在功能renderConversations,我做了以下內容:

renderConversations(){ 
    let conversationContent = this.state.conversationArray.map((conv, i) => { 
     return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}><Text style= {globalStyle.conversationText}>{ conv }</Text></View>        
    }) 
    return conversationContent 
    } 

最後,在渲染功能,我渲染{this.renderConversations()}。現在點擊按鈕觸發startConversation。 但每次我更新狀態變量的組件不更新,我做錯了什麼?

回答

3

DOC

不要直接變異this.state,使用的setState爲,對待this.state猶如 不變。


你正在一個錯誤的方式更新狀態,「永不變異的狀態值直接始終使用setState來更新它。」當我們使用setState時,自動重新呈現具有更新狀態值的組件。

寫這樣的:

this.setState(prevState => ({ 
    conversationArray: [...prevState.conversationArray, thisResponse] 
})) 

另一個問題是的setState是異步,我們不能指望更新狀態值正好的setState後,所以使用的setState回調方法並調用renderConversations內部的。

像這樣:

this.setState(prevState => ({...}),() => this.renderConversations()) 

閱讀async behaviour of setState這個答案更詳細。

建議:所有的UI邏輯應該是內部的渲染方法,所以如果你想創建用戶界面動態地調用renderConversations從渲染。

+0

正常工作。感謝您的額外提示。 :) –

+0

很高興,它解決了你的問題:) –