【问题标题】:Get API Data Using Fetch in React JS [duplicate]在 React JS 中使用 Fetch 获取 API 数据
【发布时间】:2019-01-05 18:57:00
【问题描述】:

大家好,我正在尝试通过使用 fetch 函数调用 API 来获取我的 React 组件中的数据。我的文件夹结构如下所示。

1) src->components(我所有的组件都放在这里。)

2) src->services(包含调用API函数的文件。)

下面是我的组件,我从服务文件调用函数来获取 API 数据。

import React from 'react';
import {getApiData} from '../services/';

class Dashboard extends React.Component {
  constructor(){
    super();
    this.state={
      result:''
    }
  }
  componentDidMount(){
    const data =  getApiData();
    console.log(data);
  }
  render(){
    return(
     <div></div>
    );
  }
}

export default Dashboard;

下面是我的服务文件代码,用于从 API 获取数据并返回。

  export function getApiData(){
    fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((data)=>data.json())
    .then((res)=>res)
  }

当我控制台到我的 fetch 函数时,在服务文件中使用。我得到了以下结果。

承诺 {待处理}
原型:承诺
[[PromiseStatus]]:“已解决”
[[PromiseValue]]:未定义
VM370:3 {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur ...strum rerum est autem sunt rem eveniet architecto"}

注意:我不想使用 axios。

【问题讨论】:

  • 那么使用fetch有什么问题呢?我可以看到data = getApiData() 不起作用,但我不明白你的问题,你不确定如何使用 Promises?
  • 是 /services/index.js 中的 getApiData 方法
  • 是的,@lost_in_magento 它在我的 services/index.js 文件中

标签: javascript node.js reactjs api


【解决方案1】:

在您的代码中getApiData 是承诺,但您只需在组件中调用它就可以了 首先更改 getApiData 以便我们添加 return :

 export function getApiData(){
     return fetch('https://jsonplaceholder.typicode.com/posts/1')
     .then((data)=>data.json())
     .then((res)=>res)

}

现在我们可以在 didComponet 中访问它:

componentDidMount(){
    getApiData().then(data=>{
       console.log(data);

     //or set in state
     this.setState({result:data})
     });
 }

【讨论】:

  • 这个方法我已经试过了。它不起作用。
  • @kunal 我更新了我的答案
  • 谢谢@MBehtemam,但是你能解释一下,为什么我们需要在获取之前添加return。因为我已经返回了资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2021-09-29
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多