【发布时间】:2020-09-03 02:09:14
【问题描述】:
我正在使用 React useEffect 挂钩来获取有关组件加载的 API 数据,并使用 useAxios 挂钩。代码如下(简化):
const [formData, setFormData] = useState<FormData>();
const [{ , executeGet] = useAxios('', {
manual: true,
});
const getFormData = async () => {
let r = await executeGet({ url: `http://blahblahblah/`});
return r.data;
};
useEffect(() => {
const getData = async () => {
try {
let response = await getAPIData();
if (response) {
setFormData(response);
} catch (e) {
setFormError(true);
}
};
getData();
}, []);
此模式在代码库中经常使用,但我收到了 linter 警告:
React Hook useEffect has missing dependencies: 'getFormData'. Either include them or remove the dependency array react-hooks/exhaustive-deps
我可以通过以下方式成功抑制警告:
// eslint-disable-line react-hooks/exhaustive-deps
但这样做感觉不对!
我可以毫无问题地将常量添加到依赖项列表中,但是当我添加 getFormData 函数时,我得到了一个无限循环。我已经阅读了很多有关该区域的内容,并了解为什么需要依赖项。我不确定 useEffect 钩子是否是获取数据的最佳方式,或者是否有获取数据的方法。
【问题讨论】:
标签: reactjs react-hooks use-effect