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}