【问题标题】:How can I rewrite my method to async/await?如何将我的方法重写为异步/等待?
【发布时间】:2019-03-29 21:17:54
【问题描述】:

在我的 react 应用程序中,我在 axios 的帮助下向服务器发出了一个 post 请求:

 onSubmit = (results) => {
     axios.post("http://localhost:8080/simulate/", results)
      .then( (response) => this.setState({results: response.data.results}))
      .catch( (error) => this.setState({results: error.response.data, hasError: true})
      ); 
  }

如何将此方法重写为async/await

【问题讨论】:

  • 你可以使用 request-promise,它本质上是异步的

标签: javascript ajax reactjs async-await axios


【解决方案1】:
onSubmit = async (results) => {
  try {
    const response = await axios.post("http://localhost:8080/simulate/", results)
    this.setState({results: response.data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}

编辑 - 没有 Axios

如果你不想使用 Axios,可以使用fetch api

onSubmit = async (results) => {
  try {
    const response = await fetch("http://localhost:8080/simulate/", {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(results)
    })
    const { data } = await response.json()
    this.setState({results: data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多