在上一篇文章《使用自訂 Hooks 簡化 React 中的 HTTP 請求? 》中,我們探討如何使用自訂 Hooks 簡化 HTTP 請求。雖然對於較小的應用程式有效,但隨著 React 應用程式的擴展,這種方法可能會變得更難以維護。在本文中,我們將深入探討如何使用 Axios 和 React Query 以可擴展的方式處理 CRUD(建立、讀取、更新、刪除)操作。
為什麼選擇 Axios 和 React Query?
Axios:適用於瀏覽器和 Node.js 的基於 Promise 的 HTTP 用戶端,Axios 使用乾淨、可讀的程式碼簡化了向 REST 端點發送非同步 HTTP 請求的過程。
React Query:一個強大的資料擷取庫,可增強 React 中的資料同步、快取和狀態管理。 React Query 可自動取得數據,同時提供對載入和錯誤狀態的更好控制。
設定 Axios 和 React 查詢
首先,安裝必要的軟體包:
npm install axios react-query react-router-dom
在您的應用程式中設定 React 查詢
接下來,在入口檔案 (App.tsx) 中設定 React Query 來管理應用程式的全域查詢設定。
// src/App.tsx import { QueryClient, QueryClientProvider } from 'react-query'; import { CustomRouter } from './Router'; const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, // Prevent refetch on tab/window switch retry: 1, // Retry failed queries once }, }, }); const App: React.FC = () => ( <queryclientprovider client="{queryClient}"> <customrouter></customrouter> </queryclientprovider> ); export default App;
使用攔截器設定 Axios
要處理全域身份驗證,我們可以建立一個 Axios 實例並使用攔截器為經過驗證的請求附加 Authorization 標頭。
// src/config/axiosApi.ts import axios from 'axios'; const authenticatedApi = axios.create({ baseURL: import.meta.env.VITE_BASE_URL, // Environment-specific base URL headers: { 'Content-Type': 'application/json', }, }); // Attach Authorization token to requests if present authenticatedApi.interceptors.request.use((config) => { const token = localStorage.getItem('crud-app-auth-token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); export { authenticatedApi };
為 CRUD 操作建立 API 函數
讓我們定義與 API 互動的函數,以使用 Axios 執行 CRUD 操作:
// src/data/api/post.ts import { authenticatedApi } from '../../config/axiosApi'; // Error handler function to standardize error messages export const handleApiError = (error: any): never => { if (error.message === 'Network Error') { throw new Error('Network Error. Please try again later.'); } else if (error.response?.data?.error) { throw new Error(error.response.data.error); } else if (error.response) { throw new Error('A server error occurred.'); } else { throw new Error(error.message || 'An unknown error occurred.'); } }; // General function to handle API requests export const apiCall = async <t>( method: 'get' | 'post' | 'put' | 'delete', url: string, data?: any, ): Promise<t> => { try { const response = await authenticatedApi[method](url, data); return response.data; } catch (error) { throw handleApiError(error); } }; // CRUD functions for the post feed export const createPostApi = (post: any) => apiCall<any>('post', 'posts', post); export const getPostsApi = () => apiCall<any>('get', 'posts'); export const updatePostApi = (id: string, post: any) => apiCall<any>('put', `posts/${id}`, post); export const deletePostApi = (id: string) => apiCall<any>('delete', `posts/${id}`); </any></any></any></any></t></t>
使用 React Query Hooks 進行 CRUD 操作
現在我們有了 API 函數,我們可以使用 React Query 來處理這些操作的狀態管理和資料擷取。
// src/data/hooks/post.ts import { useMutation, useQuery, useQueryClient } from 'react-query'; import { createPostApi, getPostsApi, updatePostApi, deletePostApi } from '../api/post'; // Custom hooks for CRUD operations export const useCreatePostApi = () => { const queryClient = useQueryClient(); return useMutation(createPostApi, { onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after a new post is created }); }; export const useGetPostsApi = () => useQuery(['posts'], getPostsApi); export const useUpdatePostApi = () => { const queryClient = useQueryClient(); return useMutation(updatePostApi, { onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after an update }); }; export const useDeletePostApi = () => { const queryClient = useQueryClient(); return useMutation(deletePostApi, { onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after deletion }); };
在元件中使用 CRUD 掛鉤
最後,我們可以建立一個簡單的元件,它使用自訂掛鉤並允許使用者建立、編輯和刪除貼文。
// src/components/PostCard.tsx import React, { useState } from 'react'; import { useGetPostsApi, useDeletePostApi, useUpdatePostApi, useCreatePostApi } from '../data/hooks/post'; import { toast } from '../components/Toast'; // Assume a toast component exists const PostCard: React.FC = () => { const { data: posts, isLoading, error } = useGetPostsApi(); const deletePost = useDeletePostApi(); const updatePost = useUpdatePostApi(); const createPost = useCreatePostApi(); const [newPost, setNewPost] = useState({ title: '', content: '' }); const handleCreate = async () => { try { await createPost.mutateAsync(newPost); setNewPost({ title: '', content: '' }); toast.success('Post created successfully'); } catch (error) { toast.error(error.message); } }; const handleDelete = async (id: string) => { try { await deletePost.mutateAsync(id); toast.success('Post deleted successfully'); } catch (error) { toast.error(error.message); } }; const handleEdit = async (id: string, updatedPost: any) => { try { await updatePost.mutateAsync({ id, ...updatedPost }); toast.success('Post updated successfully'); } catch (error) { toast.error(error.message); } }; if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> <div> <input type="text" value="{newPost.title}" onchange="{(e)"> setNewPost({ ...newPost, title: e.target.value })} placeholder="Title" /> <input type="text" value="{newPost.content}" onchange="{(e)"> setNewPost({ ...newPost, content: e.target.value })} placeholder="Content" /> <button onclick="{handleCreate}" disabled> {createPost.isLoading ? 'Creating...' : 'Create Post'} </button> </div> {posts?.map((post: any) => ( <div key="{post.id}"> <h3 id="post-title">{post.title}</h3> <p>{post.content}</p> <button onclick="{()"> handleEdit(post.id, { title: 'Updated Title', content: 'Updated Content' })}> Edit </button> <button onclick="{()"> handleDelete(post.id)}> Delete </button> </div> ))} </div> ); }; export default PostCard;
結論
透過使用 Axios 和 React Query,您可以簡化 React 應用程式中的 CRUD 操作。這種組合會產生乾淨、可維護的程式碼,從而提高可擴充性和效能。隨著應用程式的成長,使用這些工具可以簡化狀態管理和資料擷取。
有關 React、TypeScript 和現代 Web 開發實踐的更多見解,請在 Dev.to 上關注我! ??
以上是使用 Axios 和 React Query 回應 CRUD 操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

10款趣味橫生的jQuery遊戲插件,讓您的網站更具吸引力,提升用戶粘性!雖然Flash仍然是開發休閒網頁遊戲的最佳軟件,但jQuery也能創造出令人驚喜的效果,雖然無法與純動作Flash遊戲媲美,但在某些情況下,您也能在瀏覽器中獲得意想不到的樂趣。 jQuery井字棋遊戲 遊戲編程的“Hello world”,現在有了jQuery版本。 源碼 jQuery瘋狂填詞遊戲 這是一個填空遊戲,由於不知道單詞的上下文,可能會產生一些古怪的結果。 源碼 jQuery掃雷遊戲

本教程演示瞭如何使用jQuery創建迷人的視差背景效果。 我們將構建一個帶有分層圖像的標題橫幅,從而創造出令人驚嘆的視覺深度。 更新的插件可與JQuery 1.6.4及更高版本一起使用。 下載

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

本文演示瞭如何使用jQuery和ajax自動每5秒自動刷新DIV的內容。 該示例從RSS提要中獲取並顯示了最新的博客文章以及最後的刷新時間戳。 加載圖像是選擇

Matter.js是一個用JavaScript編寫的2D剛體物理引擎。此庫可以幫助您輕鬆地在瀏覽器中模擬2D物理。它提供了許多功能,例如創建剛體並為其分配質量、面積或密度等物理屬性的能力。您還可以模擬不同類型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流瀏覽器。此外,它也適用於移動設備,因為它可以檢測觸摸並具有響應能力。所有這些功能都使其值得您投入時間學習如何使用該引擎,因為這樣您就可以輕鬆創建基於物理的2D遊戲或模擬。在本教程中,我將介紹此庫的基礎知識,包括其安裝和用法,並提供一


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)