Flux和React:当我的应用程序发出请求时,如何显示加载指示器?好的,坏的,丑的都在尝试



我正在尝试找出隐藏/显示加载指示器的最佳方法,当我做一个请求。

我有一个:

  • LoadingAction发出一个事件来显示/隐藏加载指示器。
  • LoadingStore保存加载信息(show/hide)。
  • 加载。jsx:加载指示组件。

我尝试了不同的事情来做"通量的方式":

  • good:请求前调用LoadingAction.showLoading(),响应到达时调用LoadingAction.hideLoading()
  • bad:当我的回调从商店调用时,在每个视图中调用一个LoadingAction.showLoading()调用一个动作(发出请求)和LoadingAction.hideLoading()
  • :当我提出请求并收到响应时,我试图直接用setter方法改变LoadingStore(不是正确的解决方案…)。

但是,除了最后一次尝试("丑陋"),我总是收到错误dispatch in the middle of a dispatch

我知道这意味着什么,但我想不出其他的策略。

我不想用setTimeout函数来解决这个问题。这不是正确的解决方案。

谢谢!

经过一段时间后,我们最终得到了这里描述的解决方案。这种方法与我最初的想法非常不同:每个组件都关心加载,就像这样:

render: function(){
   // while loading
   if (!this.state.data){
     return <Loader/>
   }
   // loaded, you can use this.state.data here
   return <div>...</div>
}

但是,当API返回错误时,我们会遇到问题。在这种情况下,组件如何移除<Loader /> ?

嗯,每个组件都需要注册和侦听(我们使用Flux)来自基于承诺的HTTP客户端(Axios)的分派。这样的:

        componentDidMount: function(){
            LoaderStore.addChangeListenerEsconderLoading(this.stopLoading);
        },
        componentWillUnmount:function(){
            LoaderStore.removeChangeListenerEsconderLoading(this.stopLoading);
        },

和这个(使用Axios):

request(options)
  .then(function(response){
    success && success(response.data);
   })
   .catch(function (error) {
     LoaderAction.hideLoading();
  }

最新更新