我正在尝试构建一个自定义 Hook 来处理异步调用的加载和错误行为。
我想像这样使用它:const { loading, error} = useFetch(fetchUser, id)
或者const {loading, error } = useFetch(updateUserName, id, name)
到目前为止,我有一些看起来像这样的东西:
function useFetch(fetchFn, ...params) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
fetchFn(...params)
.then(() => {
setLoading(false);
})
.catch(() => {
setError(true);
});
}, [...params, fetchFn]);
return { loading, error };
}
我在使用
useFetch(fetchFn, ...params)
时遇到问题自新 params
每次调用时都会创建数组。所以我不能在依赖数组中使用它。但我不能使用传播运算符。是否有可能实现我正在尝试做的事情?
最佳答案
编辑:我现在使用 react-query我的生活更简单
我设法获得了想要的行为:
function useFetch(fetchFn, ...params) {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
fetchFn(...params)
.then(() => {
setLoading(false);
})
.catch(() => {
setError(true);
});
}, params);
return { loading, error };
}
我只是通过了 params
作为依赖数组。当然 eslint 不高兴,但我们可以简单地禁用它。我相信这个实现是正确的。
请随时分享您的意见,我对您的反馈很感兴趣
关于reactjs - React useEffect 在其依赖数组中有一个 spread 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59107782/