2017-12-29 2 views
2

React 상태에 문제가 있습니다. 그것은 객체 배열을받으며 상태가 올바르게 설정되어 있지만 함수가 끝나면 상태가 비어 있음을 나타냅니다. 아무도이 동작을 설명 할 수 있습니까?API 요청 후 ReactJS 상태가 업데이트됩니다.

componentDidMount() { 
    this.getWeather(); 
    this.getForecast(); 
    this.setState({location: ''}); 
    } 

    getWeather() { 
    if (this.state.location === "") { 
     this.setState({error: 'Please enter something'}); 
    } else { 
     OpenWeather.getWeather(this.state.location).then(result => { 
     if (result.cod === "404") { 
      this.setState({error: 'City not found'}); 
     } else if (result.cod === 200) { 
      this.setState({error: ''}); 
      this.setState({weather: result}); 
     } else { 
      this.setState({error: 'Server error'}); 
     } 
     }); 
    } 
    } 

    getForecast() { 
    OpenWeather.getForecast(this.state.location).then(forecast => { 
     console.log("Returned forecast:"); 
     console.log(forecast); 
     this.setState({forecast: forecast}); 
     console.log("Forecast saved to state(inside function)"); 
     console.log(this.state.forecast); 
    }); 
    console.log("Forecast saved to state(outside function)"); 
    console.log(this.state.forecast); 
    } 

콘솔 출력 :

Forecast saved to state(outside function) 
[] 
Returned forecast: 
(5) [{…}, {…}, {…}, {…}, {…}] 
Forecast saved to state(inside function) 
(5) [{…}, {…}, {…}, {…}, {…}] 
+0

이러한 질문은 getWeather() 함수는 잘 작동 및 상태를 설정하는 것을 언급하는 것을 잊었다. – bordax

답변

3

개념적으로 잘못 두 가지가 있습니다.

첫째 : OpenWeather. getForecast에 대한 귀하의 API 요청은 비동기 적이며 따라서이 실행되고 따라서 당신은 이제

Forecast saved to state(outside function) 
[] 

으로 첫 번째 응답을 한 후 API가 응답 자바 스크립트 코드를 반환하기 전에 때이 API 결과 성공, 당신은

Returned forecast: 
(5) [{…}, {…}, {…}, {…}, {…}] 

둘째 얻을 : setState를가 비동기 때문에, 세 번째 문

console.log("Forecast saved to state(inside function)"); 
console.log(this.state.forecast); 

은 업데이트 된 가치를 제공하지 않을 수도 있습니다. 대신 setState 콜백을 사용해야합니다.

확인 추가 정보를

When to use React setState callback

calling setState doesn't mutate state immediately

+0

확인. 추가 된 비동기는 거의 모든 내 Component 메소드를 기다리고 있습니다. 이제 두 함수가 모두 실행 된 후에 상태가 설정되었음을 나타내지 만 렌더링 메서드에서 상태 값에 액세스 할 수 없습니다. – bordax

+0

오류가 발생했습니다. 주소가 –

+0

에 어떻게 접근하려고합니까? 목록으로 저장됩니다. this.state.forecast [0] .main에 의해 액세스하려고 시도합니다. 상태를 하드 코딩하려고합니다. 나는 정상적인 반응을 얻는다. console.log를 conponentWillMount의 끝 부분에 추가하고 올바른 resuslts를 출력 했음. – bordax

관련 문제