Pie*_*rry 5 reactjs react-hooks
我正在尝试构建一个自定义挂钩来处理异步调用的加载和错误行为。
我想像这样使用它:
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每次调用都会创建一个新数组。所以我不能在依赖数组中使用它。但我不能使用传播运算符。
是否有可能实现我正在尝试做的事情?
编辑:我现在使用反应查询,我的生活更简单
我设法实现了想要的行为:
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 };
}
Run Code Online (Sandbox Code Playgroud)
我只是将其params作为依赖数组传递。当然 eslint 不高兴,但我们可以简单地禁用它。我相信这个实施是正确的。
请随时分享您的意见,我对您的反馈非常感兴趣
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |