2017-10-18 77 views
0

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

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:/用户/ EYAL /网络/ FE /反应/制作的Airbnb/src目录/ Homes/index.js:await是保留字(17:14)

+0

await res.json()?或者也许res.json()不返回承诺 –

回答

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

+2

'.json'是一种方法,所以它应该是'res.json()'。也许你应该补充一点 – bennygenel