无法在AJAX调用中读取未定义的属性'setState' [英] Cannot read property 'setState' of undefined in AJAX call

查看:95
本文介绍了无法在AJAX调用中读取未定义的属性'setState'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get a jsonp response from the Dark Sky API but I keep getting an undefined error. The response object and its children shows up on the console but I can't put it in the state.

这里有更多的代码:

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不支持。

I used jquery in getWeatherApi because I wanted it as jsonp and axios doesn't support that.

推荐答案

你必须绑定到外部 context

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

您也可以通过另外指定变量这个到另一个然后使用它像

You can also achieve this in another manner by assigning the variable this to another and then using it like

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

这篇关于无法在AJAX调用中读取未定义的属性'setState'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆