【发布时间】: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