2016-12-19 8 views
2

Dark Sky APIからjsonp応答を取得しようとしていますが、未定義のエラーが発生し続けます。レスポンスオブジェクトとその子はコンソールに表示されますが、私はそれを状態にすることはできません。ここAJAXコールで未定義のプロパティ 'setState'を読み取ることができません

は、コードの詳細です:

class Weather extends React.Component { 
constructor (props) { 
    super(props); 
    this.state = { 
     value: '', //user input 
     lat: 0, 
     lon: 0, //coordinates 
     data: {}, 
    } 
    this.getWeatherApi = this.getWeatherApi.bind(this); 
} 
getWeatherApi(lat,lon) { 
    var url = `https://api.darksky.net/forecast/apikey/${lat},${lon}`; 
    function setData(response) { 
     console.log(response) 
     this.setState({ 
      data: response, 
     }); 
    } 
    $.ajax({ 
     url: url, 
     dataType: 'jsonp', 
     jsonpCallback: 'setData', 
     success: function(response) { 
      setData(response) 
     } 
    }); 
} 
getLocationApi(location) { 
    var mapurl = `https://maps.googleapis.com/maps/api/geocode/json?address=${location}&key=${googlekey}`; 
    axios.get(mapurl).then(response => { 
     this.setState({ 
      lat: response.data.results[0].geometry.location.lat, 
      lon: response.data.results[0].geometry.location.lng, 
     }) 
     this.getWeatherApi(this.state.lat,this.state.lon); 
    }).catch(function (error) { 
     console.log(error); 
    }); 
} 

JSONPとaxiosはそれをサポートしていないとして、私はそれを望んでいたので、私はgetWeatherApiにjqueryのを使用しました。

+0

のようにそれを使用して別の方法でこれを達成することができ、外側context

function setData(response) { console.log(response) this.setState({ data: response, }); }.bind(this) 

に関数をbind必要があります? – guradio

+0

'setWeatherData'の' this'はあなたが想像するものではありません - 何が 'this'であるべきかを判断する方法がないので、より多くのコンテキストを表示する必要があります。 –

答えて

1

あなたがサンプルの応答を投稿することができます。また、別の変数thisを割り当て、その後

getWeatherApi(lat,lon) { 
    var url = `https://api.darksky.net/forecast/apikey/${lat},${lon}`; 
    var self = this; 
    function setData(response) { 
     console.log(response) 
     self.setState({ 
      data: response, 
     }); 
    } 
    $.ajax({ 
     url: url, 
     dataType: 'jsonp', 
     jsonpCallback: 'setData', 
     success: function(response) { 
      setData(response) 
     } 
    }); 
} 
+0

はまだ動作しません: –

+0

あなたはエラーが発生する –

+0

私は馬鹿です。私はjsonから間違った子供たちにアクセスしようとしていました。助けてくれてありがとう –

関連する問題