[英]Returning a value in a Promise
我試圖返回一個字符串值以在HTML中顯示它。 在我的HTML中,我在View中使用了Text元素(類似於React Native中的div),並嘗試用從_getCategories
方法獲得的內容填充它。 問題是我無法使該方法返回String值,因為該值是在Promise內部返回的。
現在,我試圖使此方法返回一個簡單的String值:
_getCategories = item => {
const categoryNames = [];
let fetches = [];
var allCategories = '';
for (var i = 0; i < item.categories.length; i++) {
allCategories = allCategories + item.categories[i] + ',';
}
allCategories = allCategories.substring(0, allCategories.length - 1);
fetches.push(
fetch(
'http://54.168.73.151/wp-json/wp/v2/categories?include=' + allCategories
).then(response =>
response.json().then(responseJson => {
var names = '';
for (let category of responseJson) {
names = names + category.name + ', ';
}
this.names = String(names.substring(0, names.length - 2));
console.log(this.names);
return <Text style={styles.categories}>{this.names}</Text>;
})
)
);
};
我以為這已經返回了正確的值,但是它沒有顯示在我的視圖中。 我將上述方法稱為:
<View>
{this._getCategories(item)} //this will be a text element after return
</View>
編輯:
通過對所有類別僅發出一個請求,我簡化了代碼,因此它現在應該返回一個Text對象。 不幸的是,該文本仍未顯示在我的應用中。
首先從方法中返回promise鏈:
return Promise.all(fetches).then(res => {
但是它仍然返回一個承諾,可以解決文本問題,並且無法更改它。 相反,該文本應成為組件狀態的一部分,以便xou可以在承諾解決時更新文本:
onComponentDidMount() {
this._getCategories().then(categories => this.setState({ categories }));
}
在render()
里面做:
<div>
{this.state.categories || <Text>Loading categories</Text>}
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.