如何在按钮点击事件中正确调用useFetch Hook发起数据请求
问题根源
你触发了React Hook调用规则的报错:所有Hook(包括useFetch)只能在React函数组件/自定义Hook的顶层作用域调用,不能写在点击事件回调、条件判断、循环嵌套这类非顶层作用域里。
实现方案
react-fetch-hook原生支持手动触发请求的模式,不需要把Hook塞进点击回调:通过配置项depends控制请求触发时机,初始设为不触发,点击按钮时更新依赖值即可发起请求。
完整实现代码:
import React, { useState } from 'react'; import useFetch from 'react-fetch-hook'; import { Button } from 'react-bootstrap'; const Component = () => { // 控制请求触发的标识,初始为false不发起请求 const [startFetch, setStartFetch] = useState(false); // useFetch放在组件顶层,符合Hook调用规则 // depends绑定请求触发标识,标识变化时自动发起请求 const { isLoading, data } = useFetch( 'https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json', { depends: [startFetch] } ); const handleClick = () => { // 点击时翻转标识,触发请求 setStartFetch(prev => !prev); }; return ( <div> <Button onClick={handleClick} disabled={isLoading}>Load Data</Button> <div> {!startFetch ? null : isLoading ? 'Loading...' : data ? `Received id: ${data.id}` : null} </div> </div> ); }; export default Component;
关键点说明
- 不需要额外维护
message这类冗余状态,直接根据useFetch返回的加载状态、返回数据渲染内容即可,避免多状态同步问题 - 加载过程中给按钮加
disabled属性,避免用户重复点击触发无效请求 - 如果需要重复发起相同参数的请求,直接翻转
startFetch状态即可,不需要额外写请求逻辑
内容的提问来源于stack exchange,提问作者Abel Tefera Belay
相关产品推荐
相关产品推荐

