【问题标题】:Using fetch to get data from an API in React在 React 中使用 fetch 从 API 获取数据
【发布时间】:2018-06-01 04:31:34
【问题描述】:

在 Panel.js 中,如何从我在 index.js 中编写的 API 获取数据?

面板.js

index.js

ProfilePanel.js

【问题讨论】:

  • 请编辑您的问题,以便将来为其他用户提供更多信息。链接将失效。
  • 将代码复制粘贴到您的问题中。代码图像没有那么有用。

标签: javascript reactjs api axios


【解决方案1】:

你可以使用 javascript fetch API

获取示例

fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
            .then((res) => { return res.json() })
            .then((data) => { 
                console.log(data)
                });
           })
}

POST 示例

  let key = 'key'
  let results = 12;

  fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers : new Headers(),
      body:JSON.stringify({key: key, results: results})//use property short hand here
  }).then((res) => res.json())
  .then((data) =>  console.log(data))
  .catch((err)=>console.log(err))

【讨论】:

  • 很好的例子!这应该是这个问题的答案。
【解决方案2】:

您已经收到响应并将响应映射到状态“结果”。您可以通过简单地编写“this.state.results”来显示数据

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多