2017-10-18 82 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