【问题标题】:Loading Spinner React加载微调器反应
【发布时间】:2020-05-11 17:58:40
【问题描述】:

在加载对 API 的 post 调用之前,我一直在显示进度条。我想要的是,如果 api 调用失败,请将控件导航到另一个页面,说您的连接请求失败。如果 post 调用通过,我想将其导航到成功页面。我已经编写了成功页面的代码。 API失败时如何编写。 方法:

this.setState({ loading: true });

this.sampleService.postCall(/* requestBody */)
  .then((response) => {
     const loading = this.state;
     this.setState({ loading: false });

     console.log(response);
     if(loading) {
       this.props.history.push("/success");
     }
   })
   .catch((error) => console.log(error));

任何帮助将不胜感激。

【问题讨论】:

  • 只需在catch函数中使用history.push
  • 它不起作用,在 api 失败后,我仍然看到进度微调器。 .catch((error) => { this.props.history.push("/failure") console.log(error)});
  • 那么让我们定义api failure。失败是什么意思。? wats 状态代码.. 或您期望从 API 获得的响应。 ?
  • @Singh 在您的评论中,您应该将 loading 状态设置为 false。
  • 我正在设置 loading: false, .catch((error) => { console.log("error",error) this.setState({ loading: false, }); this.props. history.push("/failure")});还是不行。

标签: javascript reactjs typescript


【解决方案1】:

您可以将then 视为success,将catch 视为fail。这意味着失败请求的代码应该在catch 块中。我正在使用我称为notifyError 的函数。如果 API 调用失败,samplService 应该拒绝 Promise。 更多信息请关注Promises documentation

this.setState({ loading: true });

this.sampleService.postCall(/* requestBody */)
  .then((response) => {
     this.setState({ loading: false });

     // I don't need to know if there is a loading state 
     // to navigate to the next page
     this.props.history.push("/success");
   })
   .catch((error) => {
      this.setState({ loading: false });
      notifyError(error); // Handle the error here
   }); 

【讨论】:

  • 我理解您的回答,但我想在 API 调用失败后立即将组件导航到不同的组件。你能帮我解决这个问题吗
  • steps = [ { name: "Step1", component: , }, { name: "Step2", component: , }, { name: "Step3",组件:,},{名称:“Step4”,组件:,},{名称:“Step5”,nextButtonText:“保存”,组件:,},{名称: '保存', 组件: , isFinishedStep: true } ];
  • 这是我正在使用向导的 UI 代码。并单击向导的最后一步,我正在执行 API 调用,如果失败我想转到 /failure 页面。我在最后一步是否需要一个 if 条件,我在哪里设置 isFinishedStep: true ?
  • 如果catch 语句中的重定向不起作用,我相信错误出现在 sampleService 中。如果请求失败,SampleService 应该拒绝承诺。
  • catch((error) => { console.log("error", error); this.setState({ finishedStep: false, }); this.props.history.push(""); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 2022-01-20
  • 2017-07-29
  • 2020-07-05
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多