【发布时间】: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