
利用ahooks的useRequest实现高效的多接口并发请求与顺序控制
在页面加载时,需要同时调用多个API接口获取数据的情况很常见。ahooks的useRequest钩子函数提供了一种简洁且高效的方式来管理这些并发请求,并灵活控制请求的执行顺序。
并发请求
useRequest默认情况下会并发执行传入的多个请求函数。例如:
<code class="javascript">import { useRequest } from 'ahooks';
const fetch1 = () => {}; // 模拟接口请求1
const fetch2 = () => {}; // 模拟接口请求2
const { data: data1, loading: loading1, error: error1 } = useRequest(fetch1);
const { data: data2, loading: loading2, error: error2 } = useRequest(fetch2);</code>这段代码会同时发起fetch1和fetch2两个接口请求。
顺序请求控制
如果接口请求之间存在依赖关系,需要按照特定顺序执行,则可以通过options参数中的manual属性来控制:
<code class="javascript">useRequest(fetch1, { manual: true });
useRequest(fetch2, { manual: true });</code>将manual设置为true后,需要手动调用run()方法来触发请求:
<code class="javascript">const ref1 = useRef(true);
const ref2 = useRef(true);
if (ref1.current) {
useRequest(fetch1).run();
ref1.current = false;
}
if (ref2.current && !loading1 && !error1) { // 确保fetch1请求完成
useRequest(fetch2).run();
ref2.current = false;
}</code>这样就保证了fetch2只有在fetch1成功完成后才会执行。
统一管理状态
useRequest返回的对象包含data、loading和error三个属性,方便统一管理多个请求的状态:
<code class="javascript">const { data: data1, loading: loading1, error: error1 } = useRequest(fetch1);
const { data: data2, loading: loading2, error: error2 } = useRequest(fetch2);
const loading = loading1 || loading2;
const error = error1 || error2;
if (!loading && !error) {
// 所有请求都成功完成
console.log('data1:', data1);
console.log('data2:', data2);
}</code>通过以上方法,您可以使用useRequest高效地管理多个API接口的并发请求和顺序,并轻松处理请求状态。
以上就是ahooks中useRequest如何实现多接口并发请求及顺序控制?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号