
理解 Composition API Vue 的基礎與模式
))} ); }; export default Swr;
fetch()
方法是從 API 獲取數據的簡單且常用的方法。它無需額外的庫支持,直接使用 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 => (
))}
);
};
export default Fetch;
React Query(也稱為 TanStack Query)是一種用于在 React 應用中管理數據的工具。它能自動處理數據的獲取、緩存和同步。
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;
Axios 是一個流行的第三方庫,用于在瀏覽器和 Node.js 中進行 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 => (
))}
);
};
export default Axios;
自定義 Hook 是 React 中的一種工具,允許開發者將邏輯封裝并在多個組件中重用。
import useFetch from "react-fetch-hook";
const UseFetch = () => {
// 使用自定義 Hook 進行數據獲取
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;
問:如何選擇合適的 API 獲取方法?
fetch()
是不錯的選擇。對于更復雜的狀態管理,React Query 或 SWR 更適合。問:使用 SWR 有哪些優勢?
問:React Query 與 Axios 有何不同?
通過本文的詳細介紹和示例代碼,希望開發者能夠在 React 項目中更高效地獲取和管理 API 數據。