【发布时间】:2020-04-15 21:26:20
【问题描述】:
我将axios 用于communicate 与服务器。我想在用户请求服务器时显示加载器并在请求完成时隐藏加载器
所以我制作了一个自定义组件来执行此任务。但是当我在同一个按钮上多次单击时,我的 UI 挂起
const Loader = () => {
const { loadingCount } = useLoadingState(),
{showLoading, hideLoading} = useLoadingActions();
useEffect(()=>{
const self = this
axios.interceptors.request.use(function (config) {
showLoading();
return config
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
// spinning hide
// self.props.loading(false)
hideLoading()
return response;
}, function (error) {
hideLoading();
return Promise.reject(error);
});
})
return (
<div>
{loadingCount > 0 ?<div style={{position:"fixed",display:"flex",justifyContent:"center",alignItems:"center",width:'100%',height:'100%',zIndex:999999}}>
{/*{loadingCount > 0 ? */}
<Spin tip="Loading..." style={{zIndex:999999}}></Spin>
{/*: null}*/}
</div>: null}
</div>
);
};
问题出在useeffect
当我注释掉 useEffect 代码时,它可以完美运行。
注意 : showloading 和 hideloading 增加和减少加载次数。
我想我已经在组件卸载时释放了 axios 对象.???
【问题讨论】:
-
效果钩子没有依赖数组,所以每次渲染都会调用它。如果效果正在更新状态/道具,它可能会产生失控效果。钩子也只适用于功能组件,没有实例,因此没有
this。
标签: javascript reactjs react-redux react-hooks