搜尋
首頁web前端js教程如何將 React 中的 REST API 與 fetch 和 Axios 集成

How to Integrate REST APIs in React with fetch and Axios

React 中的 REST API 整合

將 REST API 整合到 React 應用程式中是 Web 開發人員的常見任務。 REST(表述性狀態傳輸)是一種架構風格,可讓您透過 HTTP 方法(如 GET、POST、PUT、DELETE 等)與外部資源(資料)進行互動。 React 可以輕鬆地與 REST API 集成,從而允許您獲取資料、發布新資料並有效處理各種 API 回應。

在本指南中,我們將探索如何使用 Fetch API、Axios 等不同方法將 REST API 整合到 React 應用程式中,並處理非同步資料擷取。


1.從 REST API 取得資料

fetch() 函數內建於 JavaScript 中,提供了發出 HTTP 請求的簡單方法。它傳回一個 Promise,該 Promise 解析為表示對請求的回應的 Response 物件。

在 React 中使用 fetch API

這是一個使用 fetch API 從 REST API 取得資料並將其顯示在 React 元件中的簡單範例。

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

const API_URL = 'https://jsonplaceholder.typicode.com/posts'; // Example REST API

const FetchPosts = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch data from the API
    fetch(API_URL)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data) => {
        setPosts(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h1 id="Posts">Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key="{post.id}">
            <h2 id="post-title">{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default FetchPosts;
  • useState:用於儲存貼文、載入狀態和任何錯誤訊息。
  • useEffect:掛載組件時處理資料的取得。
  • fetch():從 REST API 端點取得數據,然後將其處理為 JSON 格式。
  • 錯誤處理:捕獲任何錯誤(例如網路問題)並設定錯誤狀態。

2.使用 Axios 進行 API 請求

Axios 是適用於瀏覽器和 Node.js 的基於 Promise 的 HTTP 用戶端。它是 fetch 的替代方案,通常因其更簡潔的語法和自動 JSON 轉換、請求取消等附加功能而受到青睞。

安裝 Axios

要使用 Axios,先透過 npm 安裝它:

npm install axios

使用axios取得資料

這裡是與上面相同的範例,但使用的是 Axios。

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_URL = 'https://jsonplaceholder.typicode.com/posts';

const FetchPosts = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch data from the API using Axios
    axios
      .get(API_URL)
      .then((response) => {
        setPosts(response.data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h1 id="Posts">Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key="{post.id}">
            <h2 id="post-title">{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default FetchPosts;
  • axios.get():從 REST API 取得資料。 Axios 會自動將回應解析為 JSON。
  • 錯誤處理:如果有錯誤,它會被捕獲並顯示在組件中。

3.將資料傳送至 REST API(POST 請求)

除了 GET 請求之外,您還可以使用 POST 請求將資料傳送到伺服器。這通常用於提交表單或建立新記錄。

使用 fetch 進行 POST 請求

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

const API_URL = 'https://jsonplaceholder.typicode.com/posts'; // Example REST API

const FetchPosts = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Fetch data from the API
    fetch(API_URL)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data) => {
        setPosts(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h1 id="Posts">Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key="{post.id}">
            <h2 id="post-title">{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default FetchPosts;
  • POST 請求:以 JSON 格式向 API 傳送資料。在本例中,我們將發送帶有標題和正文的新貼文。
  • JSON.stringify():將 JavaScript 物件轉換為請求正文的 JSON 字串。

使用 Axios 進行 POST 請求

npm install axios
  • axios.post():向 API 發送 POST 請求。請求正文包含要傳送的資料。

4.結論

將 REST API 整合到 React 應用程式中是現代 Web 開發的關鍵技能。無論您使用 fetch() 還是 Axios 等函式庫,React 都為您提供了 useEffect 和 useState 等強大的鉤子來管理 API 請求並根據回應更新 UI。您可以優雅地獲取資料、發送資料和處理錯誤,確保流暢的使用者體驗。


以上是如何將 React 中的 REST API 與 fetch 和 Axios 集成的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具