【问题标题】:if statement doesn't work on fetch requestif 语句不适用于 fetch 请求
【发布时间】:2022-07-27 00:03:39
【问题描述】:

这是一个分页功能,有时响应为空,API返回如下代码

{
  "code": "rest_post_invalid_page_number",
  "message": "Le nombre de page demandé est plus grand que le nombre de pages disponibles.",
  "data": {
    "status": 400
  }
}

为了处理这个错误,我做了一个 if 语句,但它不起作用,它直接返回 JSON

pagination = (mode) => {
      fetch(url)
        .then((response) => {
          if (!response.data.status === 400) {
            return response.json();
          } else {
         this.setState({error: 'pagination error'})
         }
        })
        .then((data) => {
          this.setState({
            data: data,
            done: true,
            loading: false,
            page: this.state.page + 1,
          });
        })
        .catch((error) => {
          console.log("error :", error);
          this.setState({
            error: error.toString(),
            loading: false,
          });
        });
  };

我还在.then(data) 中包含了代码我遇到了同样的问题

最后在 catch 错误中触发了什么

【问题讨论】:

  • 您可以根据statusCode进行操作

标签: javascript reactjs


【解决方案1】:

如果服务器正确设置了HTTP状态,你应该直接检查response.statusresponse.ok

if (response.status !== 400)
// or
if (response.ok) // status in the range 200-299

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2021-09-28
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多