Home > CMS Tutorial > WordPress > body text

React and Axios: A Beginner's Guide to API Calls

王林
Release: 2023-08-31 22:45:02
Original
700 people have browsed it

React 和 Axios:API 调用初学者指南

This tutorial will teach you how to use Axios to get data, then how to manipulate it and finally display it on your page through filtering. Along the way you'll learn how to use mapping, filters, and include methods. Most importantly, you will create a simple loader to handle the loading status of data obtained from the API endpoint.

1. Setup Project

Let’s set up a React project using the create-react-app command in the terminal:

npx create-react-app project-name
Copy after login

Then, open the project directory through a terminal window and enter npm install axios to install Axios locally for the project.

2.Select target API

We will use the Random User Generator API to get random user information to use in our application.

Let's add the Axios module to our application by importing it into our App.js file.

import axios from 'axios'
Copy after login

The Random User Generator API provides a range of options for creating various types of data. You can check out the documentation for more information, but for this tutorial we'll keep it simple.

We want to get ten different users, we just need the first name, last name, and unique ID, which is what React needs when creating the list of elements. Also, to make the call more specific, let's take the nationality option as an example.

Here is the API URL we will call:

https://randomuser.me/api/?results=10&inc=name,registered&nat=fr

Please note that I did not use the id option provided in the API as it sometimes returns null for some users. Therefore, to ensure that each user has a unique value, I included the registered option in the API.

You can copy and paste this into your browser and you will see the data returned in JSON format.

Now, the next step is to make the API call through Axios.

3. Create application state

First, let's create a state using the useState hook in React so that we can store the fetched data.

In our App component, import the useState hook from React and create the state as shown below.

import React, { useState } from "react";
import axios from "axios";

const App = () => {
  const [users, setUsers] = useState([]);
  const [store, setStore] = useState([]);

  return (
    <div>
     
    </div>
  );
};

export default App;
Copy after login

Here you can see the users and store status. One will be used for filtering purposes and will not be edited, the other will hold the filtered results that will be displayed in the DOM.

4.Use axios to obtain data

The next thing we need to do is create a getUsers function to handle the acquisition of data. In this function, we use axios to get the data from the API using the get method.

Now, in order to display the data we fetched when the page loads, we will import a React hook named useEffect and call the getUsers function in it.

useEffect The hook basically manages side effects in functional components and is similar to the componentDidMount() lifecycle hook used in React class-based components. This hook accepts an empty array as second argument for side effect cleanup.

Update the code in the App component as shown below so that we can inspect the response data in the console.

import React, { useState, useEffect } from "react";

const App = () => {
  const [users, setUsers] = useState([]);
  const [store, setStore] = useState([]);
  
  const getUsers = () => {
    axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr")
      .then(response => console.log(response))
  };
  
  useEffect(() => {
    getUsers();
  }, []);

  return (
    <div>
     
    </div>
  );
};

export default App;


Copy after login

When you check the console you will see an object output. If you open this object, there is another object inside, named data, and inside data, there is an array named results.

If we want to return a specific value from the result, we can update the axios.get call as follows:

    axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr")
      .then(response => console.log(response.data.results[0].name.first))
Copy after login

Here we record the name of the first value in the result array.

5.Processing result data

Now let’s use JavaScript’s built-in map method to iterate over each element in the array and create a new array of JavaScript objects with a new structure.

Update your getUsers function with the following code:

  const getUsers = () => {
    axios
      .get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr")
      .then((response) => {
        const newData = response.data.results.map((result) => ({
          name: `${result.name.first} ${result.name.last}`,
          id: result.registered
        }));
        setUsers(newData);
        setStore(newData);
      })
      .catch((error) => {
        console.log(error);
      });
  };
Copy after login

In the above code, we created a variable named newData. It stores the results of viewing the response.data.results array using the map method. In the map callback, we reference each element of the array as a result (note the singular/plural difference). Additionally, by using the key-value pairs for each object in the array, we create another object using the name and id key-value pairs.

一般情况下,在浏览器中查看API调用结果,会看到里面有first last 键值对name 对象,但没有全名的键值对。因此,从上面的代码中,我们能够组合 first last 名称,在新的 JavaScript 对象中创建全名。请注意,JSON 和 JavaScript 对象是不同的东西,尽管它们的工作方式基本相同。

然后我们将新的中间数据设置为 setUserssetStore 状态。

6. 通过过滤填充数据存储

过滤的想法非常简单。我们有我们的 store 状态,它始终保持原始数据不变。然后,通过在该状态上使用 filter 函数,我们只获取匹配的元素,然后将它们分配给 users 状态。

const filteredData = store.filter((item) => (
    item.name.toLowerCase().includes(event.target.value.toLowerCase()))
Copy after login

filter 方法需要一个函数作为参数,该函数针对数组中的每个元素运行。这里我们将数组中的每个元素称为 item。然后,我们获取每个 itemname 键并将其转换为小写,以使我们的过滤功能不区分大小写。

获得 itemname 键后,我们检查该键是否包含我们输入的搜索字符串。 includes 是另一个内置 JavaScript 方法。我们将在输入字段中键入的搜索字符串作为参数传递给 includes,如果该字符串包含在调用它的变量中,则它会返回。同样,我们将输入字符串转换为小写,这样无论您输入大写还是小写输入都无关紧要。

最后,filter方法返回匹配的元素。因此,我们只需将这些元素存储在 setUsers 状态中即可。

使用我们创建的函数的最终版本更新 App 组件。

 const filterNames = (event) => {
    const filteredData = store.filter((item) =>
      item.name.toLowerCase().includes(event.target.value.toLowerCase())
    );
    setUsers(filteredData);
  };
Copy after login

7. 创建组件

尽管对于这个小示例,我们可以将所有内容放入 App 组件中,但让我们利用 React 并制作一些小型功能组件。

让我们向应用程序添加几个组件。首先,我们从单独的 JavaScript 文件导入组件(我们将很快定义这些文件):

import Lists from "./components/Lists";
import SearchBar from "./components/SearchBar";
Copy after login

接下来,我们更新应用程序组件的 return 语句以使用这些组件:

  return (
    <div className="Card">
        <div className="header">NAME LIST</div>
        <SearchBar searchFunction={filterNames} />
        <Lists usernames={users} />
    </div>
  );
Copy after login

目前,我们将只关注功能。稍后我将提供我创建的 CSS 文件。

请注意,我们有 searchFunction 属性用于 SearchBar 组件,以及 usernames 属性用于 Lists 组件.

另请注意,我们使用 users 状态而不是 store 状态来显示数据,因为 users 状态包含已过滤的数据结果。

SearchBar 组件

这个组件非常简单。它仅将 filterNames 函数作为 prop,并在输入字段更改时调用该函数。将以下代码放入 components/SearchBar.js 中:

import React from 'react';

const SearchBar = ({ searchFunction}) => {
  return (
    <div>
        <input className="searchBar" type='search' onChange={searchFunction} />
    </div>
  )
};

export default SearchBar;
Copy after login

列表组件

该组件将简单地列出用户的姓名。这位于 components/List.js 中:

import React from 'react';

const Lists = ({ usernames }) => {
  return (
      <div>
          <ul>
              {usernames.map(username => (
                  <li key={username.id}>{username.name}</li>
              ))}
          </ul>
      </div>
  )
};

export default Lists;
Copy after login

在这里,我们再次使用 map 方法来获取数组中的每个项目,并从中创建一个 <li> 项目。请注意,当您使用 map 创建项目列表时,您需要使用 key 以便 React 跟踪每个列表项目。

8.跟踪加载状态

让我们使用 useState 挂钩创建一个加载状态,以显示何时尚未获取数据。

  const [loading, setLoading] = useState(false);
Copy after login

接下来,我们将更新数据获取方法中的加载状态。

  const getUsers = () => {
    axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr")
      .then((response) => {
        const newData = response.data.results.map((result) => ({
          name: `${result.name.first} ${result.name.first}`,
          id: result.registered,
        }));
        setLoading(true);
        setUsers(newData);
        setStore(newData);
      })
      .catch((error) => {
        console.log(error);
      });
  };


Copy after login

在这里,我们创建了一个 loading 状态并将其初始设置为 false。然后我们在使用 setLoading 状态获取数据时将此状态设置为 true。

最后,我们将更新 return 语句以呈现加载状态。

  return (
    <>
      {loading ? (
        <div className="Card">
          <div className="header">NAME LIST</div>
          <SearchBar searchFunction={filterNames} />
          <Lists users={users} />
        </div>
      ) : (
        <div className="loader"></div>
      )}
    </>
  );
Copy after login

使用 JavaScript 三元运算符,我们在加载状态为 false 时有条件地渲染 SearchBarLists 组件,然后在加载状态为 true 时渲染加载程序。另外,我们创建了一个简单的加载器来在界面中显示加载状态。

9. 添加一些 CSS 进行样式设置

您可以在下面找到特定于此示例的 CSS 文件。

body,
html {
  -webkit-font-smoothing: antialiased;
  margin: 0;
  padding: 0;
  font-family: "Raleway", sans-serif;
  -webkit-text-size-adjust: 100%;
}

body {
  display: flex;
  justify-content: center;
  font-size: 1rem/16;
  margin-top: 50px;
}

li,
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul {
  margin-top: 10px;
}

li {
  font-size: 0.8rem;
  margin-bottom: 8px;
  text-align: center;
  color: #959595;
}

li:last-of-type {
  margin-bottom: 50px;
}

.Card {
  font-size: 1.5rem;
  font-weight: bold;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 200px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 5px 3px 0 #ebebeb;
}

.header {
  position: relative;
  font-size: 20px;
  margin: 12px 0;
  color: #575757;
}

.header::after {
  content: "";
  position: absolute;
  left: -50%;
  bottom: -10px;
  width: 200%;
  height: 1px;
  background-color: #f1f1f1;
}

.searchBar {
  text-align: center;
  margin: 5px 0;
  border: 1px solid #c4c4c4;
  height: 20px;
  color: #575757;
  border-radius: 3px;
}

.searchBar:focus {
  outline-width: 0;
}

.searchBar::placeholder {
  color: #dadada;
}

.loader {
  border: 15px solid #ccc;
  border-top: 15px solid #add8e6; 
  border-bottom: 15px solid #add8e6;
  border-radius: 50%;
  width: 80px;
  height: 80px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
Copy after login

结论

在本教程中,我们使用随机用户生成器 API 作为随机数据源。然后,我们从 API 端点获取数据,并使用 map 方法在新的 JavaScript 对象中重构结果。

接下来是使用 filterincludes 方法创建过滤函数。最后,我们创建了两个不同的组件,并在尚未获取数据时有条件地以加载状态渲染我们的组件。

在过去的几年里,React 越来越受欢迎。事实上,我们在 Envato Market 中有许多项目可供购买、审查、实施等。如果您正在寻找有关 React 的其他资源,请随时查看它们。

The above is the detailed content of React and Axios: A Beginner's Guide to API Calls. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!