我正在尝试从Dark Sky API中获取jsonp响应,但我一直收到未定义的错误。响应对象及其子级显示在控制台上,但我无法将其置于状态。

这里是更多的代码:

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


我在getWeatherApi中使用了jquery,因为我将它作为jsonp来使用,而axios不支持它。

最佳答案

您必须bind函数到外部context

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


您还可以通过将变量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)
        }
    });
}

关于javascript - 无法读取AJAX调用中未定义的属性“setState”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41215842/

10-11 12:48