本文主要是介绍React Hooks 之 useRequest,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
基础用法 - ahooks 3.0https://ahooks.js.org/zh-CN/hooks/use-request/basic
https://hooks.umijs.org/zh-CN/hooks/asynchttps://hooks.umijs.org/zh-CN/hooks/async
一个强大的管理异步数据请求的 Hook.
核心特性
- 自动请求/手动请求
- SWR(stale-while-revalidate)
- 缓存/预加载
- 屏幕聚焦重新请求
- 轮询
- 防抖
- 节流
- 并行请求
- loading delay
- 分页
- 加载更多,数据恢复 + 滚动位置恢复
- 错误重试
- 请求超时管理
- suspense
- ...
API
const {loading: boolean,data?: TData,error?: Error,params: TParams || [],run: (...params: TParams) => void,runAsync: (...params: TParams) => Promise<TData>,refresh: () => void,refreshAsync: () => Promise<TData>,mutate: (data?: TData | ((oldData?: TData) => (TData | undefined))) => void,cancel: () => void,
} = useRequest<TData, TParams>(service: (...args: TParams) => Promise<TData>,{manual?: boolean,defaultParams?: TParams,onBefore?: (params: TParams) => void,onSuccess?: (data: TData, params: TParams) => void,onError?: (e: Error, params: TParams) => void,onFinally?: (params: TParams, data?: TData, e?: Error) => void,}
);
基础版(自动请求)
import { useRequest } from '@umijs/hooks';
import Mock from 'mockjs';
import React from 'react';function getUsername(): Promise<string> {return new Promise(resolve => {setTimeout(() => {resolve(Mock.mock('@name'));}, 1000);});
}export default () => {const { data, error, loading } = useRequest(getUsername) // 请求回调Promiseif (error) {return <div>failed to load</div>}if (loading) {return <div>loading...</div>}return <div>Username: {data}</div>
}
字段变量转换(自动请求),如data转为listData,后加:号即可。
import { useRequest } from '@umijs/hooks';
import Mock from 'mockjs';
import React from 'react';function getUsername(): Promise<string> {return new Promise(resolve => {setTimeout(() => {resolve(Mock.mock('@name'));}, 1000);});
}export default () => {const { data:listData, error, loading:isLoading } = useRequest(getUsername)if (error) {return <div>failed to load</div>}if (isLoading) {return <div>loading...</div>}return <div>Username: {listData}</div>
}
回调
const { loading, data } = useRequest(() => {return getInfo({id: xxx,});});
const { data } = useRequest(() => {return getInfo({id: xxx,})}, {onSuccess: (result, params) => {console.log('data:', data)}});
基础用法 - ahooks 3.0https://ahooks.js.org/zh-CN/hooks/use-request/basic
手动(通过设置 options.manual = true
, 则需要手动调用 run
时才会触发执行异步函数。)
import { useRequest } from '@umijs/hooks';
import { Button, Input, message } from 'antd';
import React, { useState } from 'react';
// 请求函数
function changeUsername(username: string): Promise<{ success: boolean }> {console.log(username);return new Promise(resolve => {setTimeout(() => {resolve({ success: true });}, 1000);});
}
// 默认情况下,useRequest 第一个参数是一个异步函数,在组件初始化时,会自动执行该异步函数。同时自动管理该异步函数的 loading , data , error 等状态。
export default () => {const [state, setState] = useState('');const { loading, run } = useRequest(changeUsername, {manual: true,onSuccess: (result, params) => {if (result.success) {setState('');message.success(`The username was changed to "${params[0]}" !`);}}});return (<div><InputonChange={e => setState(e.target.value)}value={state}placeholder="Please enter username"style={{ width: 240, marginRight: 16 }}/><Button onClick={() => run(state)} loading={loading}>Edit</Button></div>);
};
手动+传参+刷新
// index.tsx
const { data, run,refresh} = useRequest((id: number) => {return dataGet({id: id}) // 请求方法}, {manual: true, // 手动onSuccess: (res) => {}});useEffect(() => {run(1);}, []);// api.ts
export async function dataGet(params: any) {return request<any>(`${host}/api/info/${params.id}`, {method: 'GET',headers: { 'Content-Type': 'application/x-www-form-urlencoded'},});
}
useRequest
提供了 refresh
和 refreshAsync
方法,使我们可以使用上一次的参数,重新发起请求。
假如在读取用户信息的场景中
- 我们读取了 ID 为 1 的用户信息
run(1)
- 我们通过某种手段更新了用户信息
- 我们想重新发起上一次的请求,那我们就可以使用
refresh
来代替run(1)
,这在复杂参数的场景中是非常有用的
import { useRequest } from 'ahooks';
import Mock from 'mockjs';
import React, { useEffect } from 'react';function getUsername(id: number): Promise<string> {console.log('use-request-refresh-id', id);return new Promise((resolve) => {setTimeout(() => {resolve(Mock.mock('@name'));}, 1000);});
}export default () => {const { data, loading, run, refresh } = useRequest((id: number) => getUsername(id), {manual: true,});useEffect(() => {run(1);}, []);if (loading) {return <div>loading...</div>;}return (<div><p>Username: {data}</p><button onClick={refresh} type="button">Refresh</button></div>);
};
// 转换及整合
const { run: postRun } = useRequest((method, params) => {if (method === 'remove') {return removeFakeList(params);}if (method === 'update') {return updateFakeList(params);}return addFakeList(params);},{manual: true,onSuccess: (result) => {mutate(result);},},
);const deleteItem = (id: string) => {postRun('remove', { id });
};
其他的看官网,很丰富!
这篇关于React Hooks 之 useRequest的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!