2016-09-11 3 views
7

개방형 날씨 API에서 일부 데이터를 가져 오는 작은 반응 구성 요소를 작성했습니다. 가져 오기가 성공하고 응답에서 json 객체를 얻을 수 있습니다.반응 렌더링 메서드에서 객체 속성에 액세스

나는 다음 this.setState({})

를 사용하여 구성 요소 상태로이 응답을 저장하고 dev에 도구가 예측 객체가 상태로 저장 가리키고 있습니다 보여 반응한다.

그러나 데이터를 렌더링 할 때 항상 null의 'forecast'속성을 읽을 수 없다는 오류가 발생합니다.

다음은 반응 구성 요소와 개체 자체의 스크린 샷입니다.

export default class Weather extends Component { 
    getWeather() { 
     var self = this; 

     fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c') 
      .then (function (response) { 
       if (response.status !== 200) { 
        console.log('Looks like there was a problem. Status Code: ' + response.status); 
        return; 
       } 

       response.json().then(function(data) { 
        self.setWeather(data); 
       }); 
      }) 

      .catch (function (err) { 
       console.log('Fetch Error :-S', err); 
      }); 
    } 

    setWeather (forecast) { 
     console.log(forecast); 
     this.setState({ 
      forecast: forecast.name 
     }) 
    } 

    componentWillMount() { 
     this.getWeather(); 
    } 

    componentDidMount() { 
     // window.setInterval(function() { 
    //   this.getWeather(); 
    // }.bind(this), 1000); 
    } 

    render() { 
    return (
     <h1>{this.state.forecast}</h1> 
    ) 
    } 
} 

그리고 이것은 데이터 객체 자체이며, 지금은 단순히 name 속성에 액세스하려고합니다. 당신은 당신이 바람직 생성자에서 this에 바인딩 필요가 ComponentsetState에하기 위해, 일의 몇 잊고처럼

enter image description here

답변

3

보인다. 또한 빈 상태의 객체를 초기 상태로 설정해야하며, 객체에 전체 응답을 저장하고 원하는 부분 만 액세스 할 수 있습니다. 살펴보기 :

export default class Weather extends Component { 

constructor() { 
    super(); 
    this.state = { 
     forecast: {} 
    }; 
    this.setWeather = this.setWeather.bind(this); 
    } 

    getWeather() { 
    let self = this; 
    fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c') 
     .then (function (response) { 
     if (response.status !== 200) { 
      console.log('Looks like there was a problem. Status Code: ' + response.status); 
      return; 
     } 
     response.json().then(function(data) { 
     self.setWeather(data); 
     }); 
    }) 
    .catch (function (err) { 
     console.log('Fetch Error :-S', err); 
    }); 
    } 

    setWeather (forecast) { 
    this.setState({ 
     forecast: forecast 
    }); 
    } 

    componentWillMount() { 
    this.getWeather(); 
    } 

    render() { 
    const { forecast } = this.state; 
    return (
     <h1>{forecast.name}</h1> 
    ) 
    } 
} 
+0

너 천재 선생. 고맙습니다. – chinds

관련 문제