亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

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

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

過濾的想法非常簡單。我們有我們的 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 方法需要一個(gè)函數(shù)作為參數(shù),該函數(shù)針對(duì)數(shù)組中的每個(gè)元素運(yùn)行。這里我們將數(shù)組中的每個(gè)元素稱為 item。然后,我們獲取每個(gè) itemname 鍵并將其轉(zhuǎn)換為小寫,以使我們的過濾功能不區(qū)分大小寫。

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

最后,filter方法返回匹配的元素。因此,我們只需將這些元素存儲(chǔ)在 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)建組件

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

讓我們向應(yīng)用程序添加幾個(gè)組件。首先,我們從單獨(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 文件。

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

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

SearchBar 組件

這個(gè)組件非常簡單。它僅將 filterNames 函數(shù)作為 prop,并在輸入字段更改時(shí)調(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;

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

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

讓我們使用 useState 掛鉤創(chuàng)建一個(gè)加載狀態(tài),以顯示何時(shí)尚未獲取數(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)建了一個(gè) loading 狀態(tài)并將其初始設(shè)置為 false。然后我們?cè)谑褂?setLoading 狀態(tài)獲取數(shù)據(jù)時(shí)將此狀態(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)算符,我們?cè)诩虞d狀態(tài)為 false 時(shí)有條件地渲染 SearchBarLists 組件,然后在加載狀態(tài)為 true 時(shí)渲染加載程序。另外,我們創(chuàng)建了一個(gè)簡單的加載器來在界面中顯示加載狀態(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 對(duì)象中重構(gòu)結(jié)果。

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

在過去的幾年里,React 越來越受歡迎。事實(shí)上,我們?cè)?Envato Market 中有許多項(xiàng)目可供購買、審查、實(shí)施等。如果您正在尋找有關(guān) React 的其他資源,請(qǐng)隨時(shí)查看它們。

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)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to use the Plugin Check plugin How to use the Plugin Check plugin Jul 04, 2025 am 01:02 AM

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

See all articles