useRequest

一个强大的异步数据管理 Hook,它将数据获取逻辑中的 loading 状态、data、error、请求、取消、刷新等所有环节都封装好了。

基础用法

import { useRequest } from 'miaoma-rhooks'
import { fetchUserData } from './api'

function UserProfile({ userId }) {
    const { data, error, loading } = useRequest(() => fetchUserData(userId), {
        refreshDeps: [userId], // 当 userId 变化时,自动重新请求
        cacheKey: `user-${userId}` // 缓存数据
    })

    if (loading) return <p>Loading...</p>
    if (error) return <p>Failed to load user data.</p>

    return <div>Username: {data?.name}</div>
}

API

const { data, error, loading, run, cancel, refresh, reset } = useRequest(service, options)

Params

参数 说明 类型 默认值
service 异步请求函数 (...args: any[]) => Promise<any> -
options 配置选项 RequestOptions -

Options

参数 说明 类型 默认值
manual 是否手动触发请求 boolean false
defaultParams 默认参数 any[] []
refreshDeps 依赖数组,当依赖变化时自动重新请求 any[] []
cacheKey 缓存的键值,设置后会启用缓存 string -
cacheTime 缓存时间,单位为毫秒 number 300000 (5分钟)
onSuccess 请求成功时的回调 (data: any, params: any[]) => void -
onError 请求失败时的回调 (error: Error, params: any[]) => void -
onFinally 请求完成时的回调(无论成功或失败) (params: any[]) => void -

Result

参数 说明 类型
data 请求返回的数据 any
error 请求抛出的错误 Error
loading 请求的加载状态 boolean
run 手动触发请求的函数 (...args: any[]) => Promise<any>
cancel 取消当前请求 () => void
refresh 使用上一次的参数重新发起请求 () => Promise<any>
reset 重置请求状态 () => void

进阶用法

手动触发

import { useRequest } from 'miaoma-rhooks'
import { searchUsers } from './api'

function SearchComponent() {
    const { data, loading, run } = useRequest(searchUsers, {
        manual: true // 手动触发
    })

    return (
        <div>
            <input onChange={e => run(e.target.value)} placeholder="搜索用户" />
            {loading ? (
                <p>Loading...</p>
            ) : (
                <ul>
                    {data?.map(user => (
                        <li key={user.id}>{user.name}</li>
                    ))}
                </ul>
            )}
        </div>
    )
}

依赖刷新

import { useRequest } from 'miaoma-rhooks'
import { fetchUserPosts } from './api'

function UserPosts({ userId, category }) {
    const { data, loading } = useRequest(() => fetchUserPosts(userId, category), {
        refreshDeps: [userId, category] // 当 userId 或 category 变化时,自动重新请求
    })

    if (loading) return <p>Loading...</p>

    return (
        <div>
            <h2>用户文章</h2>
            <ul>
                {data?.map(post => (
                    <li key={post.id}>{post.title}</li>
                ))}
            </ul>
        </div>
    )
}

缓存数据

import { useRequest } from 'miaoma-rhooks'
import { fetchProductDetails } from './api'

function ProductDetail({ productId }) {
    const { data, loading } = useRequest(() => fetchProductDetails(productId), {
        cacheKey: `product-${productId}`, // 缓存键值
        cacheTime: 600000 // 缓存 10 分钟
    })

    if (loading) return <p>Loading...</p>

    return (
        <div>
            <h2>{data?.name}</h2>
            <p>{data?.description}</p>
            <p>价格: {data?.price}</p>
        </div>
    )
}

错误处理

import { useRequest } from 'miaoma-rhooks'
import { submitForm } from './api'
import { message } from 'antd'

function SubmitForm() {
    const { loading, run } = useRequest(submitForm, {
        manual: true,
        onSuccess: data => {
            message.success('提交成功!')
        },
        onError: error => {
            message.error(`提交失败: ${error.message}`)
        }
    })

    const handleSubmit = values => {
        run(values)
    }

    return (
        <Form onFinish={handleSubmit}>
            {/* 表单内容 */}
            <Button loading={loading} type="primary" htmlType="submit">
                提交
            </Button>
        </Form>
    )
}