2017-10-18 6 views
0

어떻게 비동기 구문으로 다음 코드를 변경할 수 있습니까?가져 오기를 async 구문으로 변경하십시오.

componentWillMount(){ 
    const res = await fetch('http://localhost:9000/api/homes'); 
    const json = await res.json; 
       this.setState({ 
        originalList:json, 
        displayedList: json 
       }); 
} 

나는 다음과 같은 오류가 발생합니다 :

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}`); 
      }); 
} 

나는 같이 그것을 위해 노력했다 구문 오류 : C :/사용자/Eyal 님/웹/FE/반응/에어 비앤비/SRC/Homes/index.js : await는 예약어입니다.

+0

res.json()을 기다리고 있습니까? 또는 res.json() 약속을 반환하지 않습니다 –

답변

1

await을 사용하려면 componentWillMount 메서드를 async으로 선언해야합니다. 당신은 서명을 변경하여 해당 작업을 수행 할 수 있습니다 : 그것은 res.json()을해야하므로

async componentWillMount() { 
    const res = await fetch('http://localhost:9000/api/homes'); 
    const json = await res.json(); 
    this.setState({ 
    originalList: json, 
    displayedList: json 
    }); 
} 

또한 .json는 방법이다. (감사합니다 bennygenel)

+2

'.json' 메서드는'res.json()'이어야합니다. 어쩌면 당신은 그것을 추가해야합니다. – bennygenel