如何根据post http方法响应状态设置setState?

时间:2019-04-30 11:18:08

标签: javascript reactjs async-await ecmascript-7

当我从后端(http post方法)获得响应时,我尝试在React中设置状态。我要做的是将数据发送到服务器,然后在resp返回时,我想将isSubmitting属性设置为false。话虽如此,我的状态并不依赖于响应的数据->仅依赖于响应状态。返回响应后如何设置状态?

我不想只是console.log此内容,我想在内容准备好后制作this.setState({ isSubmitting })

我想到了类似的东西: if (content) { this.setState({ isSubmitting }) }

但是dunno是正确的。

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();

我已通过替换异步/等待来解决问题,从而解决了问题:

    return fetch('https://httpbin.org/post', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(blabla)
    })
    .then(resp => resp.json())
    .then(resp => console.log(resp));

所以现在我可以在最后一行设置setState了。但是我仍然很好奇它如何与承诺一起工作。

1 个答案:

答案 0 :(得分:0)

根据this文章,您甚至不需要创建content变量,并且可以很好地检查响应是否正常(如果您使用的是fetch -在ok属性中。)

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  if (rawResponse.ok) {
    this.setState({ isSubmitting: false }); 
  }
})();

依赖于await函数体内的async关键字的任何操作/语句都将等待其解决然后执行。