javascript - 在ReactJS中获取数据

标签 javascript reactjs fetch

componentDidMount()中有一个get请求

componentDidMount() {
   var manufacturers = []

   this.props.participants.map(participant => {
     Get("manufacturer/" + participant.id, "").then(result => {
      manufacturers.push(result)
      console.log(manufacturers)
    });
  });

  this.setState({
    participants: manufacturers
  })
}

这个console.log(manufacturers)显示数组中有对象,但组件的状态为空。获取数据后如何正确设置?

Get()函数代码:

const Config = require('Config')
export async function Get(type, userData) {
    let BaseURL = Config.serverUrl;
    let result = {};
    if(userData)
        result = await fetch(BaseURL+type, {
                method: 'GET',
                headers: new Headers({
                    'Authorization': 'Bearer ' + userData,
                    'Content-Type': 'application/json'
                })
        });
    else
        result = await fetch(BaseURL+type, {
            method: 'GET',
            headers: new Headers({
                'Content-Type': 'application/json'
            })
        });
    let data = await result.json();
    return data;
}

最佳答案

由于您要进行多个 Get 调用,并且每个调用都是异步,因此您必须等到收集到所有结果然后将其设置为状态。您可以使用 Promise.all 来实现,它可以先等待所有 Get 调用得到解析,然后将数据设置为状态。

我首先创建一个 async 函数并在 componentDidMount 中调用它。

componentDidMount() {
  this.fetchAllData();
}

然后在这个方法中,等待所有Promises被解析,并在我们获得数据后将其设置为状态。您可能必须将整个函数包装在 try..catch block 中,以便如果由于网络调用失败而导致任何 Promise 拒绝,您可以适本地处理它。

fetchAllData = async () => {
  const manufacturers = await Promise.all(
    this.props.participants.map(participant => 
      Get("manufacturer/" + participant.id, ""))
  )
  this.setState(manufacturers)
};

关于javascript - 在ReactJS中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514672/

相关文章:

javascript - 无法使用 fetch API 获取数据

javascript - 如何通过下面提到的对象的索引获取第一个对象

javascript - 如何使用来自 React Router 的路由参数发出 axios 请求,然后根据响应更新状态?

node.js - React js代码: 'MODULE_NOT_FOUND' ,无法运行reactjs?

reactjs - 开 Jest : Cannot find module 'react' , 和其他 node_modules

javascript - 使用 POST 方法设置跨源 Cookie

javascript - 隐藏聊天室脚本直到单击按钮

javascript - 如何使用 Angular 2 添加背景图片伪元素 'after' 内容?

javascript - Jquery 属性未添加到 div 元素

security - 如何处理 native react 中的 OAuth2 token 刷新?