【问题标题】:fetch url in javascript returns empty array在javascript中获取url返回空数组
【发布时间】:2020-05-14 09:06:29
【问题描述】:

我编写这段代码是为了从 API 获取数据。但我只是在控制台上看到 []

enter image description here 我想我必须使用Promiseasync/await,但我不知道该怎么做。

【问题讨论】:

  • 为什么你只是用图像替换了代码?太糟糕了....您不能从图像中复制和粘贴!
  • 因为我的代码没有正确显示在屏幕上。

标签: javascript reactjs


【解决方案1】:

Here 是一个与您正在做的非常相似的示例:

// FILE: App.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
class App extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }
  componentDidMount() {
    fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`)
      .then(res => res.json())
      .then(json => this.setState({ data: json }));
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.data.map(el => (
            <li>
              {el.name}: {el.price_usd}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}
export default App;
ReactDOM.render(<App />, document.getElementById("app"));

Async/Await 是使用 then/promise 链接的替代方案。换句话说,你不需要 async/await。

【讨论】:

    【解决方案2】:

    当您输出到控制台时,您的 fetch 尚未完成(即点击 then() 回调)。

    如果您想查看检索到的数据,请在将表数据设置为返回值后,尝试将输出放在第二个 then() 回调中。

    【讨论】:

    • 我把我的代码改成了这个:fetch(this.getLink(), { headers: { 'Content-Type': 'application/json' } }) .then(response =&gt; response.json()) .then(TableData =&gt; function() { console.log(TableData); this.setState({TableData}) }) .catch(error =&gt; console.debug(error));但这没关系
    • @LastRemaining 关闭。试着把它放在 this.setState(...) 之后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 2021-12-16
    • 1970-01-01
    • 2021-08-12
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多