【发布时间】:2018-10-06 22:08:30
【问题描述】:
我正在尝试返回一个字符串值以在我的 HTML 中显示它。在我的 HTML 中,我在 View 中使用 Text 元素(类似于 React Native 中的 div),并尝试用我从方法 _getCategories 中获得的内容填充它。问题是我不能让该方法返回一个字符串值,因为该值是在 Promise 中返回的。
现在,我试图让这个方法返回一个简单的字符串值:
_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.all 返回另一个promise,因此您的整个函数仍然返回一个可以解析为您的字符串的promise。
-
其实我的错,它没有返回任何东西,因为你没有返回 Promise.all
标签: javascript json promise