useRequest 是一个来自 ahooks 库的 Hook,它可以帮助我们更方便地处理网络请求。下面是一个基本的用法介绍:
基本用法
import { useRequest } from 'ahooks';
function fetchData() {
  return fetch('https://api.example.com/data')
    .then((response) => response.json())
    .then((data) => data.list);
}
function MyComponent() {
  const { data, error, loading } = useRequest(fetchData);
  if (loading) {
    return <div>加载中...</div>;
  }
  if (error) {
    return <div>错误:{error.message}</div>;
  }
  return (
    <div>
      <h1>数据列表</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}
在上面的例子中,我们定义了一个 fetchData 函数,该函数返回一个 Promise,它将从 API 中获取数据。然后,我们使用 useRequest Hook 将这个函数传递给它,并将其返回的状态对象解构出来。
状态对象中包含三个属性:
- data:请求成功后的数据
- error:请求失败后的错误信息
- loading:请求是否正在进行中
我们可以根据这些状态来渲染不同的 UI。
options
useRequest 还提供了一些选项,可以帮助我们更好地控制请求的行为。例如:
- pollingInterval:指定请求的轮询间隔时间,以毫秒为单位。
- retry:指定请求失败后的重试次数。
- retryInterval:指定请求失败后的重试间隔时间,以毫秒为单位。
- cacheKey:指定缓存的 key,以便在下次请求时可以从缓存中获取数据。
以下是一个使用选项的示例:
import { useRequest } from 'ahooks';
function fetchData() {
  return fetch('https://api.example.com/data')
    .then((response) => response.json())
    .then((data) => data.list);
}
function MyComponent() {
  const { data, error, loading } = useRequest(fetchData, {
    pollingInterval: 3000, // 每 3 秒轮询一次
    retry: 3, // 请求失败后重试 3 次
    retryInterval: 1000, // 重试间隔为 1 秒
    cacheKey: 'my-cache-key' // 缓存的 key
  });
  //...
}
manual
如果我们想要手动控制请求的执行,可以使用 useRequest 的 manual 选项。例如:
import { useRequest } from 'ahooks';
function fetchData() {
  return fetch('https://api.example.com/data')
    .then((response) => response.json())
    .then((data) => data.list);
}
function MyComponent() {
  const { run, data, error, loading } = useRequest(fetchData, {
    manual: true // 手动控制请求的执行
  });
  const handleClick = () => {
    run(); // 手动执行请求
  };
  //...
}
在上面的例子中,我们使用 manual 选项来手动控制请求的执行。然后,我们可以使用 run 函数来手动执行请求。
这些就是 useRequest 的基本用法和选项。如果你需要更多的自定义,可以查看 ahooks 的文档。