【问题标题】:Making two calls in same function在同一个函数中进行两次调用
【发布时间】:2019-01-21 17:07:16
【问题描述】:

我有两个请求,一个 GET 和一个 POST 请求,我正在获取 GET 请求并在数组内部设置响应状态,我想将此数组传递给 POST 请求正文,然后我正在获取 POST 请求所以我可以打电话,问题是它没有在 GET 调用中设置状态,它总是返回未定义,我不知道为什么,这里是代码:

我的构造函数:

constructor(props){
  super(props);
  this.state = {
    info: [],
  }
}

功能:

myFunction = async () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response });
      fetch("https://myapp.com/submit_info", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: this.state.info.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};

【问题讨论】:

  • React 的 setState 调用也是异步的。您应该只使用来自GET 请求的数组结果作为POST 请求的输入。我认为没有必要在下一个请求之前先将其保存到状态。
  • 查看 React 中 setState 的文档。它是异步的,因此需要像 this.setState({ info: response}, () => { ...second fetch here }) 这样的回调

标签: javascript api react-native fetch


【解决方案1】:

您忘记返回承诺,然后使用 response 对象设置 infoID 字段而不是状态,因为对 this.setState 的调用是异步的,并且在您进行第二次 api 调用时仍将处于挂起状态。

myFunction = () => {
  fetch("https://myapp.com/info", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "x-auth-token": token
    }
  })
    .then(res => res.json())
    .then(response => {
      this.setState({ info: response }); // async call
      return fetch("https://myapp.com/submit_info", {
        // return promise for chaining
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-auth-token": token
        },
        body: JSON.stringify({
          infoID: response.id
        })
      })
        .then(res => res.json())
        .then(result => {
          console.log(result);
        });
    })
    .catch(error => console.log(error));
};

【讨论】:

  • 你应该添加一个注意,这里设置反应状态对第二个请求没有影响。
  • 是的,这就是为什么我建议使用第一个 api 调用的响应对象而不是状态。
猜你喜欢
  • 1970-01-01
  • 2017-09-13
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多