搜尋
首頁web前端js教程使用 useEffect、Promises 和自訂 Hooks 處理 React 中的非同步操作

Handling Async Operations in React with useEffect, Promises, and Custom Hooks

在 React 中處理非同步呼叫

處理非同步操作是 React 應用程式中的常見要求,尤其是在使用 API、資料庫或外部服務時。由於 JavaScript 操作(例如從 API 獲取資料或執行計算)通常是非同步的,因此 React 提供了工具和技術來優雅地處理它們。

在本指南中,我們將使用 async/awaitPromises 和其他 React 特定工具來探索在 React 中處理非同步呼叫的不同方法。


1.使用 useEffect 進行非同步呼叫

React 的 useEffect 鉤子非常適合執行副作用,例如在元件安裝時取得資料。鉤子本身不能直接返回承諾,因此我們在效果中使用非同步函數。

在 useEffect 中使用 async/await

以下是如何使用 useEffect 掛鉤處理非同步呼叫以取得資料。

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

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

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

  // Using async/await inside useEffect
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(API_URL);
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData(); // Call the async function
  }, []); // Empty dependency array means this effect runs once when the component mounts

  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 AsyncFetchExample;
  • async/await:處理基於 Promise 的獲取過程。
  • 錯誤處理:捕獲錯誤並顯示適當的訊息。
  • 載入狀態:管理載入並顯示載入指示器,直到取得資料。

為什麼要使用非同步/等待?

  • 簡化程式碼:避免需要 .then() 和 .catch() 鏈。
  • 更乾淨、更具可讀性:Promise 可以更線性的方式處理。

2.使用 Promise 進行非同步操作

另一種常見方法是直接將 Promises 與 then() 和 catch() 結合使用。這種方法不如 async/await 優雅,但在 JavaScript 中仍然廣泛用於處理非同步操作。

在 useEffect 中使用 Promise

這是一個使用 Promise 和 then() 進行非同步呼叫的範例:

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

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

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

  useEffect(() => {
    fetch(API_URL)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        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 AsyncFetchWithPromise;
  • then():成功解決 Promise。
  • catch():捕獲 API 呼叫期間發生的任何錯誤。
  • 錯誤處理:如果請求失敗,則顯示錯誤訊息。

3.使用 useReducer 實現複雜的非同步邏輯

當您有更複雜的狀態轉換或需要在非同步過程中處理多個操作(如載入、成功、錯誤)時,useReducer 是管理狀態變更的絕佳工具。

使用 useReducer 進行非同步操作

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

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

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

  // Using async/await inside useEffect
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(API_URL);
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData(); // Call the async function
  }, []); // Empty dependency array means this effect runs once when the component mounts

  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 AsyncFetchExample;
  • useReducer:針對複雜非同步邏輯的更強大的狀態管理工具。
  • 多個操作:分別處理不同的狀態,如載入、成功和錯誤。

4.使用自訂掛鉤實作可重複使用非同步邏輯

在某些情況下,您可能希望跨多個元件重複使用非同步邏輯。建立自訂鉤子是封裝邏輯並使程式碼更可重複使用的絕佳方法。

建立用於取得資料的自訂鉤子

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

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

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

  useEffect(() => {
    fetch(API_URL)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        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 AsyncFetchWithPromise;
  • 自訂 Hook (useFetch):封裝了取得資料、錯誤處理、載入狀態的邏輯。
  • 可重複使用性:鉤子可以在任何需要取得資料的元件中重複使用。

5.結論

在 React 中處理非同步操作對於建立現代 Web 應用程式至關重要。透過使用 useEffect、useReducer 和自訂鉤子等鉤子,您可以輕鬆管理非同步為、處理錯誤並確保流暢的使用者體驗。無論您是獲取資料、處理錯誤還是執行複雜的非同步邏輯,React 都為您提供了強大的工具來有效管理這些任務。


以上是使用 useEffect、Promises 和自訂 Hooks 處理 React 中的非同步操作的詳細內容。更多資訊請關注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

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

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器