【问题标题】:Change fetch to async syntax将 fetch 更改为异步语法
【发布时间】:2018-03-30 07:11:54
【问题描述】:

如何将以下代码更改为异步语法?

componentWillMount(){
 fetch('http://localhost:9000/api/homes')
          .then( response => {
              if(response.ok) {
                  return response.json();
              }
              throw new Error('Network response was not ok.');    
          })
          .then( data => {
              this.setState({
                  originalList:data,
                  displayedList: data
              });
          }
        )
          .catch( error => {
              console.error(`fetch operation failed: ${error.message}`);
          });
}

我尝试过这样做:

componentWillMount(){
  const res = await fetch('http://localhost:9000/api/homes');
  const json = await res.json;
              this.setState({
                  originalList:json,
                  displayedList: json
              });
}

我收到以下错误:语法错误:C:/Users/EYAL/web/fe/react/airbnb/src/Homes/index.js: await is a reserved word (17:14)

【问题讨论】:

  • 等待 res.json()?或者 res.json() 没有返回承诺

标签: reactjs async-await fetch


【解决方案1】:

您必须将componentWillMount 方法声明为async 才能使用await。您可以通过更改签名来做到这一点:

async componentWillMount() {
  const res = await fetch('http://localhost:9000/api/homes');
  const json = await res.json();
  this.setState({
    originalList: json,
    displayedList: json
  });
}

另外.json 是一个方法,所以它应该是res.json()。 (感谢bennygenel

【讨论】:

  • .json 是一个方法,所以它应该是res.json()。也许你也应该添加它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
相关资源
最近更新 更多