什么是 ahooks?
ahooks 是一個 React Hooks 庫,提供了大量實用的自定義 hooks,幫助開發者更高效地構建 React 應用。其中場景類 hooks 是 ahooks 的一個重要分類,專門針對特定業務場景提供解決方案。
安裝 ahooks
npm install ahooks
常用場景類 hooks 詳解
網絡請求場景 – useRequest
useRequest
是 ahooks 中最核心的 hooks 之一,用于處理異步請求。
import React from "react";
import { useRequest } from "ahooks";const UserList = () => {const { data, loading, error, run } = useRequest(async () => {const response = await fetch("/api/users");return response.json();},{manual: true, // 手動觸發onSuccess: (result) => {console.log("請求成功:", result);},onError: (error) => {console.log("請求失敗:", error);},});return (<div><button onClick={run} disabled={loading}>{loading ? "加載中..." : "獲取用戶列表"}</button>{error && <div>錯誤: {error.message}</div>}{data && (<ul>{data.map((user) => (<li key={user.id}>{user.name}</li>))}</ul>)}</div>);
};
高級特性
// 輪詢請求
const { data } = useRequest(fetchUserData, {pollingInterval: 3000, // 每3秒輪詢一次pollingWhenHidden: false, // 頁面隱藏時停止輪詢
});// 防抖請求
const { data } = useRequest(searchUsers, {debounceWait: 500, // 500ms防抖
});// 緩存請求
const { data } = useRequest(fetchUserData, {cacheKey: "userData",staleTime: 5 * 60 * 1000, // 5分鐘內數據不重新請求
});
表單場景 – useAntdTable
useAntdTable
用于處理表格與表單的聯動場景。
import React from "react";
import { useAntdTable } from "ahooks";
import { Form, Input, Button, Table } from "antd";const UserTable = () => {const [form] = Form.useForm();const { tableProps, search } = useAntdTable(async (params, form) => {const { current, pageSize } = params;const response = await fetch("/api/users", {method: "POST",body: JSON.stringify({page: current,size: pageSize,...form,}),});const data = await response.json();return {list: data.list,total: data.total,};},{form,defaultPageSize: 10,});return (<div className="container m-4"><Form form={form} layout="inline" className="mb-2"><Form.Item name="name" label="姓名"><Input placeholder="請輸入姓名" /></Form.Item><Form.Item name="email" label="郵箱"><Input placeholder="請輸入郵箱" /></Form.Item><Form.Item><Button type="primary" onClick={search.submit}>搜索</Button><Button onClick={search.reset} style={{ marginLeft: 8 }}>重置</Button></Form.Item></Form><Table{...tableProps}columns={[{ title: "姓名", dataIndex: "name" },{ title: "郵箱", dataIndex: "email" },{ title: "創建時間", dataIndex: "createTime" },]}/></div>);
};
狀態管理場景 – useLocalStorageState
useLocalStorageState
用于在 localStorage 中持久化狀態。
import React from "react";
import { useLocalStorageState } from "ahooks";const ThemeSwitcher = () => {const [theme, setTheme] = useLocalStorageState("theme", {defaultValue: "light",serializer: (value) => JSON.stringify(value),deserializer: (value) => JSON.parse(value),});return (<div><p>當前主題: {theme}</p><button onClick={() => setTheme("light")}>淺色主題</button><button onClick={() => setTheme("dark")}>深色主題</button></div>);
};
生命周期場景 – useMount & useUnmount
import React from "react";
import { useMount, useUnmount } from "ahooks";const UserProfile = () => {useMount(() => {console.log("組件掛載,開始獲取用戶信息");// 初始化邏輯});useUnmount(() => {console.log("組件卸載,清理資源");// 清理邏輯});return <div>用戶信息</div>;
};
事件處理場景 – useEventListener
import React, { useState } from "react";
import { useEventListener } from "ahooks";const KeyboardListener = () => {const [key, setKey] = useState("");useEventListener("keydown", (event) => {setKey(event.key);});return (<div><p>按下的鍵: {key}</p></div>);
};
工具類場景 – useDebounce & useThrottle
import React, { useState } from "react";
import { useDebounce, useThrottle } from "ahooks";const SearchComponent = () => {const [value, setValue] = useState("");const debouncedValue = useDebounce(value, 500);const throttledValue = useThrottle(value, 1000);return (<div><inputvalue={value}onChange={(e) => setValue(e.target.value)}placeholder="輸入搜索內容"/><p>原始值: {value}</p><p>防抖值: {debouncedValue}</p><p>節流值: {throttledValue}</p></div>);
};
媒體查詢場景 – useResponsive
import React from "react";
import { useResponsive } from "ahooks";const ResponsiveComponent = () => {const responsive = useResponsive();return (<div><p>屏幕尺寸信息:</p><ul><li>xs: {responsive.xs ? "是" : "否"}</li><li>sm: {responsive.sm ? "是" : "否"}</li><li>md: {responsive.md ? "是" : "否"}</li><li>lg: {responsive.lg ? "是" : "否"}</li><li>xl: {responsive.xl ? "是" : "否"}</li></ul></div>);
};
滾動場景 – useScroll
import React from "react";
import { useScroll } from "ahooks";const ScrollComponent = () => {const scroll = useScroll(document);return (<div style={{ height: "200vh" }}><div style={{ position: "fixed", top: 0, left: 0 }}><p>滾動位置: {scroll?.left || 0}, {scroll?.top || 0}</p><p>滾動方向: {scroll?.direction || "none"}</p></div></div>);
};
總結
ahooks 的場景類 hooks 為 React 開發提供了強大的工具集,能夠顯著提升開發效率:
- useRequest: 處理異步請求的完整解決方案
- useFormTable: 表格與表單聯動的便捷工具
- useLocalStorageState: 狀態持久化
- useMount/useUnmount: 生命周期管理
- useEventListener: 事件監聽
- useDebounce/useThrottle: 性能優化
- useResponsive: 響應式設計
- useScroll: 滾動處理
通過合理使用這些 hooks,可以大大簡化 React 應用的開發復雜度,提高代碼的可維護性和用戶體驗。