2017-11-27 18 views
1
getSelectedCityId() { 
    let citiName 
    citiId; 
    axiosInstance 
     .get("/api/cities") 
     .then(response => { 
      if (response.status === 200 && response.data) { 
       citiName = this.state.city; 
       citiId = this.state.city.city_id; 
      } 
     }) 
     .catch(error => {}); 

    let url = `/api/${citiName}/${citiId}/schools/`; 
    axiosInstance 
     .get(url) 
     .then(response => { 

     }) 
     .catch(error => { 
      console.log(error); 
     }); 
} 

, URL은 보여줍니다ES6의 템플릿 리터럴에 동적 값을 전달할 수 있습니까? 내가 그 API 호출을 칠 때

로컬 호스트 : 9000/API/정의되지 않은/정의되지 않은/학교/

내가 통과하려고 해요 데이터를 두 번째 API에 매개 변수로 첫 번째 API 호출에서 얻을 것이다. 내 요점은, 왜 템플릿 리터럴 정의되지 않은 던지고있다? 템플릿 리터럴을 통해 동적 데이터를 전달할 수 있습니까?

+1

비동기 프로세스의 일부인 변수를 설정하려고하므로이 경우 작동하지 않을 수 있습니다. [이 질문과 답변을 통해 비동기 호출 응답을 반환하는 방법] (https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call)을 읽어야합니다. ? rq = 1). – Andy

+0

PS - [async/wait'를 사용한 경우] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)이 인스턴스에서 향상된 코딩 경험을 누릴 수 있습니다. . [빌드 프로세스에 포함시켜야합니다] (https://stackoverflow.com/questions/38357234/is-it-possible-to-use-async-await-in-react-js). – Andy

+0

@Andy 좀 알아 냈습니다! 귀하의 의견을 보내 주셔서 감사합니다! – Technologeek

답변

3
getSelectedCityId() { 
    let citiName 
    citiId; 
    axiosInstance 
     .get("/api/cities") 
     .then(response => { 
      if (response.status === 200 && response.data) { 
       citiName = this.state.city; 
       citiId = this.state.city.city_id; 
       this.getSelectedCityIdStepTwo(`/api/${citiName}/${citiId}/schools/`); 
      } 
     }) 
     .catch(error => {}); 
} 

getSelectedCityIdStepTwo(url) { 
    axiosInstance 
     .get(url) 
     .then(response => { 

     }) 
     .catch(error => { 
      console.log(error); 
     }); 
} 

이 두 번째 Axios의의 호출이되지 않도록하고 전달하는 유효한 URL이 있습니다.

3

/api/cities 데이터를 가져 오는 것이 비동기 작업이므로 결과를 기다려야합니다. 그냥 개념의 증명 : 첫 번째가 완료 될 때까지

getSelectedCityId() 
{ 
    let citiName 
    citiId; 
    axiosInstance 
    .get("/api/cities") 
    .then(response => { 
     if (response.status === 200 && response.data) { 
     citiName = this.state.city; 
     citiId = this.state.city.city_id; 
     return `/api/${citiName}/${citiId}/schools/`; 
     } 
     return null; 
    }) 
    .then(url => { 
     if(url) { // the data from previous then 
     axiosInstance.get(url) //.then().catch() 
     } 
    }); 
} 
+0

이것은 내 것보다 더 간결한 대답입니다. 나는 너희에게 굴복 할 것이다! –

+0

@ JoshuaUnderwood 동의합니다. 그러나 분해가 좋습니다. 더 작은 함수로 코드를 작성하면 읽기 및 디버깅이 쉬워집니다. 어쨌든 솔루션을 함께 사용했습니다. – Technologeek

+0

다음은 승인 된 답변으로 표시해야합니다.) –