繁体   English   中英

为什么获取的承诺没有解决(反应)

[英]Why is promise from fetch not resolving (react)

我是 promises 和 async/await 的新手。 我一直在阅读,但我仍然不明白为什么我的getDate()方法的承诺没有解决。

我一直在捆绑许多解决方案,但结果都是一样的,一个未解决的承诺。 这是我正在使用的代码。

async getData() {
  await this.syncLedgerSum(
    "http://localhost:5000/webapi/getorders"
  ).then(response => this.setState({ items: response }));

  //this works, state.items is displayed on browser console
  //console.log("State Items in getData is : ", this.state.items);
  return this.state.items;
}

async syncLedgerSum(URL) {
  const response = await fetch(URL, {
    method: "GET"
  });
  console.log("syncLedgerSum Response: ", response);

  const json = await response.json();
  console.log("syncLedgerSum json: ", json);
  return json;
}

async componentDidMount() {
    console.log("Component Did mount: ");
    let data = await this.getData();
    if (data) console.log("Items in Component Did mount is : ", data);
}

上图显示了我正在使用的代码的日志。

在此处输入图像描述

我不知道为什么请求没有完成。 如何将数据存储到state.items中以呈现该信息?

由于您处理响应的方式。 请参阅工作代码笔

使用 await,您不必使用.then来处理承诺响应。

async getData() {
  const response = await this.syncLedgerSum(
    "http://localhost:5000/webapi/getorders"
  )

  this.setState({ items: response })
  //this is not a sync call, so you can either await or use the response instead but setState should trigger another render. not sure what you need this for. 

  return response;
}

您可以使用npm install axiosyarn add axios

 getData() { axios.get("http://localhost:5000/webapi/getorders").then(function (response) { console.log(response) this.setState({ items: response }) }).catch(function (error) { console.log(error) this.setState({ items: [] }) }) }

componentDidMount你调用函数getData()

暂无
暂无

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

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