【问题标题】:How to setState depending on post http method response status?如何根据 post http 方法响应状态设置状态?
【发布时间】:2019-09-19 01:05:48
【问题描述】:

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

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

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

但不知道是不是正确的。

(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);
})();

我已经通过替换 async/await 来解决问题:

    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));

所以现在我可以在最后一行设置状态。但我仍然很好奇它是如何与 Promise 一起工作的。

【问题讨论】:

  • 当然,当您想更新组件状态中的任何内容时,您应该使用this.setState。请注意this.setState({ isSubmitting }) 会将状态的isSubmitting 属性设置为变量isSubmitting 的值,因此请确保已定义。
  • 是的,我知道 setState 是方法。但是何时放置正确的代码?低于content 声明?不会是同步的,isSubmitting 将在实际数据返回之前设置?
  • 是的,在那里。你试过了吗? await 的全部意义在于它“等待”promise 被解析,允许您编写异步代码,就好像它是同步的一样。
  • 是的,我试过了,但不知道是否正确。我在某处读到它仅在包含的部分上“等待” - 在这种情况下,content 变量。但我不想使用contentisSubmitting 状态设置为false

标签: javascript reactjs async-await ecmascript-2016


【解决方案1】:

根据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 函数体内的动作/语句都会等待它解析然后执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2021-07-21
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多