简体   繁体   English

ReactJS-.map函数内的REST API查询?

[英]ReactJS - REST API query inside .map function?

How do I generate repetitive mark-up elements in a React component, that also require a REST API query for each of them? 如何在React组件中生成重复的标记元素,而每个元素也都需要REST API查询? Initially I had the calls completing in a for-each loop within the componentDidMount function. 最初,我在componentDidMount函数内的for-each循环中完成了调用。 But that required calling setState inside the loop, in order to trigger a re-Render. 但这需要在循环内调用setState才能触发重新渲染。 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). 所以,现在我试图让查询在我的渲染器的.map函数中运行(见下文)。 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...) (可能更多的是JS问题而不是React问题...)
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. 似乎您想查询所有API,然后在所有问题解决后处理响应。

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. 然后在render()函数中渲染this.state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM