如何在 ReactJS 中使用 JSON 服务器获取 API 调用

作者 : 慕源网 本文共1956个字,预计阅读时间需要5分钟 发布时间: 2021-10-30 共440人阅读

介绍

在本文中,我们将学习如何在 React 应用程序中使用 JSON 服务器获取 API 调用。 

现在我们将开始创建一个新项目。 

第1步 

使用以下命令创建 React 项目设置,或者创建 React 应用程序。 

npx create-react-app projectname

例子, 

npx create-react-app sample-fetch 

第 2 步 – 安装 React JSON-server

由于 JSON Server 可用作 NPM 包,因此我们可以使用 Node.js 包管理器执行安装。 

在终端中运行以下命令。

npm install Json-server 

第 3 步 – 创建一个包含数据的示例 JSON 文件 

JSON Server 将从您的主项目文件夹中获取一个 JSON 文件,并将其转换为具有所有正确路由的 RESTful 数据库。 

我在新创建的项目中使用以下示例数据创建了一个 JSON 文件db.json。 

{
    "posts": [{
        "id": 1,
        "name": "Satheesh",
        "email": "Sat@mail.com",
        "adderss": "South street"
    }, {
        "id": 2,
        "name": "John",
        "email": "john@mail.com",
        "adderss": "North street"
    }, {
        "id": 3,
        "name": "Robert",
        "email": "robert@mail.com",
        "adderss": "East street"
    }, {
        "id": 4,
        "name": "Mani",
        "email": "mani@mail.com",
        "adderss": "West street"
    }],
    "comments": [{
        "id": 1,
        "body": "some comment",
        "postId": 1
    }],
    "profile": {
        "name": "typicode"
    }
}

第 4 步 – 运行服务器

通过执行以下命令启动 JSON 服务器。

json-server –watch db.json 

我们的 JSON 服务器将在端口 3000 上运行。 

第 5 步 – 获取 API

  • 它在现代浏览器中可用,并允许我们使用 JavaScript 承诺发出请求。 
  • 我们可以使用 fetch() 方法来获取数据。
  • 要使用 fetch 发出简单的 GET 请求,它包括我们要向其发出请求的 URL 端点 
  • 使用 Fetch API 获取所有帖子的列表。(端点http://localhost:3000/posts 等由已经运行的 JSON 服务器提供) 
  • App 组件 (App.js) 的状态并填充用户状态变量
getFetchUsers() {
    this.setState({
        loading: true
    }, () => {
        fetch("http://localhost:3000/posts").then(res => res.json()).then(result => this.setState({
            loading: false,
            users: result
        })).catch(console.log);
    });
}

在获取 API 调用中,

首先是返回 JSON 对象

第二个是打印值。

第 6 步

Src/App.js

import React, {
    Component
} from 'react';
class App extends React.Component {
        state = {
            isLoading: true,
            users: [],
            error: null
        };
        getFetchUsers() {
            this.setState({
                loading: true
            }, () => {
                fetch("http://localhost:3000/posts").then(res => res.json()).then(result => this.setState({
                    loading: false,
                    users: result
                })).catch(console.log);
            });
        }
        componentDidMount() {
            this.getFetchUsers();
        }
        render() {
            const {
                users,
                error
            } = this.state;
            return (
              <React.Fragment>
              <h1>All User</h1>
              {
                    error ? <p>
              {
                        error.message
                    } < /p> : null}  {
                        users.map(user => {
                            const {
                                adderss,
                                name,
                                email
                            } = user;
                            return (
                            <div key={name}>
                                <p>Name: {name}</p>
                                <p>Email: {email}</p>
                                <p>Address: {adderss}</p>
                                <hr />
                            </div>
                            );
                        })
                    } < /React.Fragment> );
            }
        }
export default App;

第 7 步

现在我们将运行应用程序。

npm run start 

成功执行上述命令后,它将显示浏览器, 


慕源网 » 如何在 ReactJS 中使用 JSON 服务器获取 API 调用

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录