[英]How do I prevent a function from being run before data is loaded into this.state (i.e. in componentDidMount)?
我有一個函數getRepresentativeName()
它使用來自this.state
的一段數據( this.state.communityData.Representative
)來索引到數據庫並檢索一個字符串。 我的意圖是,當組件安裝時, this.state
所有信息,包括this.state.communityData.Representative
,都將被填充,並且代表的名字將出現在由{...}設置的位置。 但是,該函數在調用第一次渲染時立即運行,不會等待組件掛載; 作為一個結果,因為this.state
未填充然而,getRepresentativeName功能崩潰。
我放了一個三元語句來檢查communityData JSON對象是否被填充(邏輯是如果沒有填充,即==={},只返回null
而不是executing getRepresenativeName())
; 有趣的是,網頁崩潰不管(有相同的問題: getRepresenativeName()
之前被稱為this.state
中填充componentDidMount()
有人可以向我解釋為什么會發生這種情況,以及如何在不向this.state
添加冗余數據的情況下解決這種情況? 我不確定這是否是解決它的方法,但我認為如果有一種方法可以讓getRepresentativeName()
函數等到componentDidMount()
完成,則可以解決問題。 謝謝!
注意:如果我不調用該函數而只是將{...}替換為{ this.state.communityData.Representative} ,這會使用代表 ID 而非名稱填充元素,頁面呈現完美。 此外,我嘗試將getRepresentative
name getRepresentative
回調,但仍然無效(即頁面在嘗試呈現時仍然崩潰)。
async getRepresentativeName() {
const representativeSnapshot = await database()
.ref('users')
.child(this.state.communityData.Representative)
.child('name')
.once('value');
return representativeSnapshot.val();
};
render() {
console.log('starting render');
return (
<View style={styles.containerScreen} testID="communityScreen">
{/*
This the container that holds the community Image
and its description,
*/}
<View style={styles.containerhorizontal}>
<View style={styles.containervertical}>
<Image
source={require('../../sample_images/va10.jpg')}
style={styles.image}
/>
</View>
<View style={styles.containervertical}>
<Text style={styles.containerhorizontal}>
Description: {this.state.communityData.Description}
</Text>
<Text style={styles.containerhorizontal}>
Representative: **{this.state.communityData !== {} ?this.getRepresentativeName() : null}**
</Text>
...
這里的典型模式是使用某種加載屬性初始化您的狀態。 然后,根據來自用戶界面的輸入異步加載數據。 該輸入可能來自用戶,也可能來自生命周期事件。 在這種情況下,componentDidMount。 您的組件應該知道如何在加載為真和數據可用時進行渲染。
class MyComponent extends React.Component {
state = {loading: true, error: null, representative: null}
componentDidMount() {
fetchData().then((representative) => {
this.setState({ loading: false, representative })
}).catch((error) => {
this.setState({ loading: false, error: error.message })
})
}
render() {
return this.state.error
? <span>woops</span>
: this.state.loading
? <span>busy</span>
: <div>Representative: {this.state.representative.name}</div>
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.