在React中进行API调用 [英] Making an API call in React

查看:166
本文介绍了在React中进行API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在React中进行API调用以返回JSON数据,但是我对此却有些困惑.文件API.js中的我的API代码如下:

I am trying to make an API call in React to return JSON data but I am a bit confused on how to go about this. My API code, in a file API.js, looks like this:

import mockRequests from './requests.json'

export const getRequestsSync = () => mockRequests

export const getRequests = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(mockRequests), 500)
})

正在检索格式如下的JSON数据:

It is retrieving JSON data formatted like this:

{
"id": 1,
"title": "Request from Nancy",
"updated_at": "2015-08-15 12:27:01 -0600",
"created_at": "2015-08-12 08:27:01 -0600",
"status": "Denied"
 }

目前,我进行API调用的代码如下:

Currently my code to make the API call looks like this:

import React from 'react'

const API = './Api.js'

const Requests = () => ''

export default Requests

我看了几个例子,但对于如何解决这个问题仍然有些困惑.如果有人能指出我正确的方向,将不胜感激.

I've looked at several examples and am still a bit confused by how to go about this. If anyone could point me in the right direction, it would be greatly appreciated.

在我见过的大多数示例中,尽管我在语法上苦苦挣扎,但获取似乎是解决问题的最佳方法

In most examples I've seen, fetch looks like the best way to go about it, though I'm struggling with the syntax

推荐答案

以下是使用实时API的简单示例( https: //randomuser.me/)...它返回一个对象数组,如您的示例:

Here is a simple example using a live API (https://randomuser.me/)... It returns an array of objects like in your example:

import React from 'react';

class App extends React.Component {
  state = { people: [], isLoading: true, error: null };

  async componentDidMount() {
    try {
      const response = await fetch('https://randomuser.me/api/');
      const data = await response.json();
      this.setState({ people: data.results, isLoading: false });

    } catch (error) {
      this.setState({ error: error.message, isLoading: false });
    }
  }

  renderPerson = () => {
    const { people, isLoading, error } = this.state;

    if (error) {
      return <div>{error}</div>;
    }

    if (isLoading) {
      return <div>Loading...</div>;
    }

    return people.map(person => (
      <div key={person.id.value}>
        <img src={person.picture.medium} alt="avatar" />
        <p>First Name: {person.name.first}</p>
        <p> Last Name: {person.name.last}</p>
      </div>
    ));
  };

  render() {
    return <div>{this.renderPerson()}</div>;
  }
}

export default App;

这有意义吗?应该很简单...

Does it make sense? Should be pretty straight forward...

此处的实时演示: https://jsfiddle.net/o2gwap6b/

Live Demo Here: https://jsfiddle.net/o2gwap6b/

这篇关于在React中进行API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆