Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 将fetch更改为异步语法_Reactjs_Async Await_Fetch - Fatal编程技术网

Reactjs 将fetch更改为异步语法

Reactjs 将fetch更改为异步语法,reactjs,async-await,fetch,Reactjs,Async Await,Fetch,如何将以下代码更改为异步语法 componentWillMount(){ fetch('http://localhost:9000/api/homes') .then( response => { if(response.ok) { return response.json(); } throw new Error('Network response

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

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是一个保留字(17:14)

为了使用
await
,您必须将
组件willmount
方法声明为
async
。您可以通过更改签名来执行此操作:

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()
。(谢谢)

为了使用
wait
,您必须将
组件willmount
方法声明为
async
。您可以通过更改签名来执行此操作:

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()
。(谢谢)

wait res.json()?或者res.json()不返回PromiseWait res.json()?或者可能res.json()不返回promise
。json
是一种方法,因此它应该是
res.json()。也许你也应该加上它。
.json
是一种方法,所以它应该是
res.json()
。也许你也应该加上这个