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()
。也许你也应该加上这个