我正在尝试构建一个自定义挂钩来处理异步调用的加载和错误行为。
我想像这样使用它:
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 };
}
Run Code Online (Sandbox Code Playgroud)
我遇到了麻烦,useFetch(fetchFn, ...params)因为params每次调用都会创建一个新数组。所以我不能在依赖数组中使用它。但我不能使用传播运算符。
是否有可能实现我正在尝试做的事情?