How do I generate repetitive mark-up elements in a React component, that also require a REST API query for each of them? Initially I had the calls completing in a for-each loop within the componentDidMount function. But that required calling setState inside the loop, in order to trigger a re-Render. The behavior was unstable, and apparently that technique is not a good idea.
So, now I'm trying to get the queries to run inside the .map function of my render (see below). But that's producing this error .
Is there a way to return the element value instead of a promise? (Probably more of a JS question than a React one...)
Or am I going about this the wrong way altogether?
return (<div>
{this.props.currentProject.Tasks.map((task => {
return ProjectsService.getTaskBaselines(this.props.currentProject.PWAGuid, task.TaskId, this.props.context).then((baseline: any): any => {
return (<div>{task.TaskName}</div>);
})
}))}
</div>);
It seems like you want to query all APIs and then handle the response once all are settled.
Try this:
const promises = this.props.currentProject.Tasks.map((task => {
return new Promise(function(resolve, reject) {
resolve(task);
});
Promise.all(promises).then((data) => {
this.setState({
// act on all of your data
});
});
Then render this.state
in your render()
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.