国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
SearchBar 組件
列表組件
結(jié)論
Home CMS Tutorial WordPress React and Axios: A Beginner's Guide to API Calls

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

Aug 31, 2023 pm 10:45 PM

React 和 Axios:API 調(diào)用初學(xué)者指南

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

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'

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;

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;


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))

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);
      });
  };

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調(diào)用結(jié)果,會看到里面有first last 鍵值對name 對象,但沒有全名的鍵值對。因此,從上面的代碼中,我們能夠組合 first last 名稱,在新的 JavaScript 對象中創(chuàng)建全名。請注意,JSON 和 JavaScript 對象是不同的東西,盡管它們的工作方式基本相同。

然后我們將新的中間數(shù)據(jù)設(shè)置為 setUserssetStore 狀態(tài)。

6. 通過過濾填充數(shù)據(jù)存儲

過濾的想法非常簡單。我們有我們的 store 狀態(tài),它始終保持原始數(shù)據(jù)不變。然后,通過在該狀態(tài)上使用 filter 函數(shù),我們只獲取匹配的元素,然后將它們分配給 users 狀態(tài)。

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

filter 方法需要一個函數(shù)作為參數(shù),該函數(shù)針對數(shù)組中的每個元素運(yùn)行。這里我們將數(shù)組中的每個元素稱為 item。然后,我們獲取每個 itemname 鍵并將其轉(zhuǎn)換為小寫,以使我們的過濾功能不區(qū)分大小寫。

獲得 itemname 鍵后,我們檢查該鍵是否包含我們輸入的搜索字符串。 includes 是另一個內(nèi)置 JavaScript 方法。我們將在輸入字段中鍵入的搜索字符串作為參數(shù)傳遞給 includes,如果該字符串包含在調(diào)用它的變量中,則它會返回。同樣,我們將輸入字符串轉(zhuǎn)換為小寫,這樣無論您輸入大寫還是小寫輸入都無關(guān)緊要。

最后,filter方法返回匹配的元素。因此,我們只需將這些元素存儲在 setUsers 狀態(tài)中即可。

使用我們創(chuàng)建的函數(shù)的最終版本更新 App 組件。

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

7. 創(chuàng)建組件

盡管對于這個小示例,我們可以將所有內(nèi)容放入 App 組件中,但讓我們利用 React 并制作一些小型功能組件。

讓我們向應(yīng)用程序添加幾個組件。首先,我們從單獨(dú)的 JavaScript 文件導(dǎo)入組件(我們將很快定義這些文件):

import Lists from "./components/Lists";
import SearchBar from "./components/SearchBar";

接下來,我們更新應(yīng)用程序組件的 return 語句以使用這些組件:

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

目前,我們將只關(guān)注功能。稍后我將提供我創(chuàng)建的 CSS 文件。

請注意,我們有 searchFunction 屬性用于 SearchBar 組件,以及 usernames 屬性用于 Lists 組件.

另請注意,我們使用 users 狀態(tài)而不是 store 狀態(tài)來顯示數(shù)據(jù),因?yàn)?users 狀態(tài)包含已過濾的數(shù)據(jù)結(jié)果。

SearchBar 組件

這個組件非常簡單。它僅將 filterNames 函數(shù)作為 prop,并在輸入字段更改時調(diào)用該函數(shù)。將以下代碼放入 components/SearchBar.js 中:

import React from 'react';

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

export default SearchBar;

列表組件

該組件將簡單地列出用戶的姓名。這位于 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;

在這里,我們再次使用 map 方法來獲取數(shù)組中的每個項(xiàng)目,并從中創(chuàng)建一個 <li> 項(xiàng)目。請注意,當(dāng)您使用 map 創(chuàng)建項(xiàng)目列表時,您需要使用 key 以便 React 跟蹤每個列表項(xiàng)目。

8.跟蹤加載狀態(tài)

讓我們使用 useState 掛鉤創(chuàng)建一個加載狀態(tài),以顯示何時尚未獲取數(shù)據(jù)。

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

接下來,我們將更新數(shù)據(jù)獲取方法中的加載狀態(tài)。

  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);
      });
  };


在這里,我們創(chuàng)建了一個 loading 狀態(tài)并將其初始設(shè)置為 false。然后我們在使用 setLoading 狀態(tài)獲取數(shù)據(jù)時將此狀態(tài)設(shè)置為 true。

最后,我們將更新 return 語句以呈現(xiàn)加載狀態(tài)。

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

使用 JavaScript 三元運(yùn)算符,我們在加載狀態(tài)為 false 時有條件地渲染 SearchBarLists 組件,然后在加載狀態(tài)為 true 時渲染加載程序。另外,我們創(chuàng)建了一個簡單的加載器來在界面中顯示加載狀態(tài)。

9. 添加一些 CSS 進(jìn)行樣式設(shè)置

您可以在下面找到特定于此示例的 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); }
}

結(jié)論

在本教程中,我們使用隨機(jī)用戶生成器 API 作為隨機(jī)數(shù)據(jù)源。然后,我們從 API 端點(diǎn)獲取數(shù)據(jù),并使用 map 方法在新的 JavaScript 對象中重構(gòu)結(jié)果。

接下來是使用 filterincludes 方法創(chuàng)建過濾函數(shù)。最后,我們創(chuàng)建了兩個不同的組件,并在尚未獲取數(shù)據(jù)時有條件地以加載狀態(tài)渲染我們的組件。

在過去的幾年里,React 越來越受歡迎。事實(shí)上,我們在 Envato Market 中有許多項(xiàng)目可供購買、審查、實(shí)施等。如果您正在尋找有關(guān) 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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the WordPress testing environment How to use the WordPress testing environment Jun 24, 2025 pm 05:13 PM

Use WordPress testing environments to ensure the security and compatibility of new features, plug-ins or themes before they are officially launched, and avoid affecting real websites. The steps to build a test environment include: downloading and installing local server software (such as LocalWP, XAMPP), creating a site, setting up a database and administrator account, installing themes and plug-ins for testing; the method of copying a formal website to a test environment is to export the site through the plug-in, import the test environment and replace the domain name; when using it, you should pay attention to not using real user data, regularly cleaning useless data, backing up the test status, resetting the environment in time, and unifying the team configuration to reduce differences.

How to use Git with WordPress How to use Git with WordPress Jun 26, 2025 am 12:23 AM

When managing WordPress projects with Git, you should only include themes, custom plugins, and configuration files in version control; set up .gitignore files to ignore upload directories, caches, and sensitive configurations; use webhooks or CI tools to achieve automatic deployment and pay attention to database processing; use two-branch policies (main/develop) for collaborative development. Doing so can avoid conflicts, ensure security, and improve collaboration and deployment efficiency.

How to create a simple Gutenberg block How to create a simple Gutenberg block Jun 28, 2025 am 12:13 AM

The key to creating a Gutenberg block is to understand its basic structure and correctly connect front and back end resources. 1. Prepare the development environment: install local WordPress, Node.js and @wordpress/scripts; 2. Use PHP to register blocks and define the editing and display logic of blocks with JavaScript; 3. Build JS files through npm to make changes take effect; 4. Check whether the path and icons are correct when encountering problems or use real-time listening to build to avoid repeated manual compilation. Following these steps, a simple Gutenberg block can be implemented step by step.

How to set up redirects in WordPress htaccess How to set up redirects in WordPress htaccess Jun 25, 2025 am 12:19 AM

TosetupredirectsinWordPressusingthe.htaccessfile,locatethefileinyoursite’srootdirectoryandaddredirectrulesabovethe#BEGINWordPresssection.Forbasic301redirects,usetheformatRedirect301/old-pagehttps://example.com/new-page.Forpattern-basedredirects,enabl

How to send email from WordPress using SMTP How to send email from WordPress using SMTP Jun 27, 2025 am 12:30 AM

UsingSMTPforWordPressemailsimprovesdeliverabilityandreliabilitycomparedtothedefaultPHPmail()function.1.SMTPauthenticateswithyouremailserver,reducingspamplacement.2.SomehostsdisablePHPmail(),makingSMTPnecessary.3.SetupiseasywithpluginslikeWPMailSMTPby

How to flush rewrite rules programmatically How to flush rewrite rules programmatically Jun 27, 2025 am 12:21 AM

In WordPress, when adding a custom article type or modifying the fixed link structure, you need to manually refresh the rewrite rules. At this time, you can call the flush_rewrite_rules() function through the code to implement it. 1. This function can be added to the theme or plug-in activation hook to automatically refresh; 2. Execute only once when necessary, such as adding CPT, taxonomy or modifying the link structure; 3. Avoid frequent calls to avoid affecting performance; 4. In a multi-site environment, refresh each site separately as appropriate; 5. Some hosting environments may restrict the storage of rules. In addition, clicking Save to access the "Settings>Pinned Links" page can also trigger refresh, suitable for non-automated scenarios.

How to make a WordPress theme responsive How to make a WordPress theme responsive Jun 28, 2025 am 12:14 AM

To implement responsive WordPress theme design, first, use HTML5 and mobile-first Meta tags, add viewport settings in header.php to ensure that the mobile terminal is displayed correctly, and organize the layout with HTML5 structure tags; second, use CSS media query to achieve style adaptation under different screen widths, write styles according to the mobile-first principle, and commonly used breakpoints include 480px, 768px and 1024px; third, elastically process pictures and layouts, set max-width:100% for the picture and use Flexbox or Grid layout instead of fixed width; finally, fully test through browser developer tools and real devices, optimize loading performance, and ensure response

How to integrate third-party APIs with WordPress How to integrate third-party APIs with WordPress Jun 29, 2025 am 12:03 AM

Tointegratethird-partyAPIsintoWordPress,followthesesteps:1.SelectasuitableAPIandobtaincredentialslikeAPIkeysorOAuthtokensbyregisteringandkeepingthemsecure.2.Choosebetweenpluginsforsimplicityorcustomcodeusingfunctionslikewp_remote_get()forflexibility.

See all articles