promise的状态值,在Promise中返回值

I am trying to return a String value to display it in my HTML. In my HTML, I'm using a Text element in a View (similar to a div in React Native) and try to fill it with that that I'm getting from the method _getCategories. The problem is that I can't make the method return a String value, since the value is returned inside a Promise.

Now, I'm trying to make this method return a simple String value:

_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 {this.names};

})

)

);

};

I thought this returns the correct value already, but it's not showing in my View. I call the method above as follows:

{this._getCategories(item)} //this will be a text element after return

Edit:

I have simplified my code by making only one request for all categories together, so it should probably return a the Text object now. Unfortunately, the text is still not showing in my app.

解决方案

First of all return the promise chain from the method:

return Promise.all(fetches).then(res => {

but then it still returns a promise resolving somewhen to a text, and there is no way to change that. Instead that text should be part of the components state, so that xou can update the text when the promise resolves:

onComponentDidMount() {

this._getCategories().then(categories => this.setState({ categories }));

}

And inside render() just do:

{this.state.categories || Loading categories}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值