2016-08-28 90 views
0

獲得初始狀態,我想顯示狀態值從已經從componenDidMount稱爲異步函數渲染(),但在第一執行部件,它返回不確定的,對於第二次嘗試它顯示正確的數據陣營原住民從異步componentDidMount

這是我的狀態this.state.userData

我的問題是,什麼是優先處理功能渲染()和componentDidMount()?

這是我的代碼

componentDidMount: function(){ 
    store.get('userData').then((val) => { 
     if(typeof val != 'undefined'){ 
      this.setState({'userData':val}); 
     } 
    }).done(); 
}, 
render: function() { 
    return(
     <View> 
       <Text>{this.state.userData}</Text> // displaying undefined 
     </View> 
    ); 
} 
+1

它似乎代碼工作,因爲它應該。主線程不會被使用promise對象阻塞(這是obj的承諾)。調用渲染函數store.get(..)後,它會查找userData,但它在第一次渲染中不存在,因爲setState({'userData':val})沒有工作並導致第二次渲染。如果你在getInıtıalState()中用''空字符串添加這個狀態,你將看不到未定義的狀態。你正試圖解決在componentdid mount中未定義的問題,但沒有任何問題。 –

回答

4

我不知道你在問什麼。

據我所知:你想在render()被調用之前執行一個函數來設置數據。 在這種情況下:查看生命週期方法 - >link。它很好地解釋說你可以在調用render之前使用componentWillMount()。 enter image description here

但是:這並不能保證您在調用渲染前擁有數據。我建議你設置一個額外的狀態變量來知道什麼時候異步調用完成,然後才調用一個加載微調器。

喜歡的東西:

constructor(props){ 
super(props); 
this.state={ 
    loading: true 
} 
} 
在功能

this.setState({userData:val, loading: false}); 

渲染:

render() { 
if(this.state.loading){ 
    return(<ActivityIndicator size='large' style={{height:80}} /> 
} 
else{ 
return(
    <View> 
      <Text>{this.state.userData}</Text> // displaying undefined 
    </View> 
); 
} 

(應該只給一個想法 - 代碼是即興..但應該解決未定義的問題) 玩得開心

+0

感謝您的信息 我更新componentDidMount到componentWillMount但在我的情況,我需要等待結果,因爲我使用承諾函數來獲取價值,它使結果在第一次嘗試組件 –

+0

未定義那麼,爲什麼不疏導呈現到不同的東西直到你有「店鋪」的結果?在這種情況下,你一定不要弄不明白 – dv3