显示正在加载axios发布请求

时间:2018-09-26 19:44:35

标签: javascript reactjs

我想为我的Axios请求创建一个加载

代码是

atribuiImagem() {
  const { atribuiFormState, loadingAtribuiImagens } = this.state;
  const data = {
    id_lote: atribuiFormState.values.batch,
    id_user: atribuiFormState.values.username,
    tipo: atribuiFormState.values.result
  };
  this.setState({ loadingAtribuiImagens: true });
  if (
    data.id_lote !== undefined &&
    data.id_user !== undefined &&
    data.tipo !== undefined
  ) {
    axios
      .post(`${API_URL}/list`, data, getAxiosConfig())
      .then(function() {
        toast.success("Imagem atribuida com sucesso.", toastConfig);
      })
      .catch(function() {
        toast.error("Tente outra vez.", toastConfig);
      });
  } else {
    toast.error("Tente outra vez.", toastConfig);
  }
  this.setState({ atribuiFormState, loadingAtribuiImagens: false });
}

然后我有一个组件名称正在加载

const Loading = () => (
  <div className="loading-style text-center">
    <img src={loader} className="loading" alt="Carregando..." />
  </div>
);

导出默认加载; 我想在发送POST请求时使此“加载”组件在屏幕上呈现给用户,但实际上我找不到一种实现方法。

2 个答案:

答案 0 :(得分:0)

如您所知,设置状态是异步的,并且还会响应批处理状态更新。因此,如果将loading设置为true,然后立即设置为false,则您的加载器将永远不会显示。这就是这段代码中发生的事情。您将loading设置为true,然后立即设置为false。

在.then和.catch中移动以下行

this.setState({ loadingAtribuiImagens: false })

也可以在将状态设置为true时在if条件内移动它。 这样您的最终代码将变为

if(/* your condition */) {
    /* set loading to true*/
    /* set loading to false when your promise get resolved or rejected */
}

答案 1 :(得分:0)

尝试:

atribuiImagem = () => {
const { atribuiFormState, loadingAtribuiImagens } = this.state;
const data = {
  id_lote: atribuiFormState.values.batch,
  id_user: atribuiFormState.values.username,
  tipo: atribuiFormState.values.result
};

if(data.id_lote !== undefined && data.id_user !== undefined && data.tipo !== undefined)
 {
 this.setState({ loadingAtribuiImagens: true });
 axios
  .post(`${API_URL}/list`, data, getAxiosConfig())
  .then(data => {
    this.setState({ atribuiFormState, loadingAtribuiImagens: false });
    toast.success("Imagem atribuida com sucesso.", toastConfig);
  })
  .catch(error => {
    this.setState({ atribuiFormState, loadingAtribuiImagens: false });
    toast.error("Tente outra vez.", toastConfig);
  });
 }
else{
  this.setState({ atribuiFormState, loadingAtribuiImagens: false });
  toast.error("Tente outra vez.", toastConfig);
 }      
}