))} ); }; export default Swr;

2. 使用 JavaScript 的 Fetch() 方法

fetch() 方法是從 API 獲取數(shù)據(jù)的簡單且常用的方法。它無需額外的庫支持,直接使用 JavaScript 原生功能。

import { useState, useEffect } from 'react';

const Fetch = () => {
  const [photos, setPhotos] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/photos')
      .then(res => res.json())
      .then(data => setPhotos(data));
  }, []);

  return (
    
{photos.map(photo => ( {photo.title} ))}
); }; export default Fetch;

3. 使用 React Query 庫

React Query(也稱為 TanStack Query)是一種用于在 React 應(yīng)用中管理數(shù)據(jù)的工具。它能自動(dòng)處理數(shù)據(jù)的獲取、緩存和同步。

import { useQuery } from '@tanstack/react-query';

const Query = () => {
  const { data: comments, isLoading, error } = useQuery({
    queryFn: () => fetch('https://jsonplaceholder.typicode.com/comments?_limit=10').then(res => res.json()),
    queryKey: ['comments'],
  });

  if (isLoading) return 

Loading...

; if (error) return
Error: error fetching
; return (

Email address of users

{comments.map(comment => (

{comment.id}. {comment.email}

))}
); }; export default Query;

4. 使用 Axios 庫

Axios 是一個(gè)流行的第三方庫,用于在瀏覽器和 Node.js 中進(jìn)行 HTTP 請求。

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

const Axios = () => {
  const [meals, setMeals] = useState([]);

  useEffect(() => {
    axios.get('https://www.themealdb.com/api/json/v1/1/random.php')
      .then(res => setMeals(res.data.meals));
  }, []);

  return (
    
{meals.map(meal => ( {meal.strMeal} ))}
); }; export default Axios;

5. 使用自定義 Hook – useFetch

自定義 Hook 是 React 中的一種工具,允許開發(fā)者將邏輯封裝并在多個(gè)組件中重用。

import useFetch from "react-fetch-hook";

const UseFetch = () => {
  // 使用自定義 Hook 進(jìn)行數(shù)據(jù)獲取
  const { isLoading, data, error } = useFetch("https://jsonplaceholder.typicode.com/users");

  if (isLoading) return 

Loading...

; if (error) return

Error occurred: {error.message}

; return (
{data.map(user => (

{user.name}

))}
); }; export default UseFetch;

FAQ

  1. 問:如何選擇合適的 API 獲取方法?

  2. 問:使用 SWR 有哪些優(yōu)勢?

  3. 問:React Query 與 Axios 有何不同?

通過本文的詳細(xì)介紹和示例代碼,希望開發(fā)者能夠在 React 項(xiàng)目中更高效地獲取和管理 API 數(shù)據(jù)。

上一篇:

OptiFine 是 Forge 還是 Fabric?全面解析與使用指南

下一篇:

人人都是 API 設(shè)計(jì)者:我對(duì) RESTful API、GraphQL、RPC API 的思考
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)