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

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

问题描述

我正在尝试从 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.

推荐答案

您必须将函数bind 到外部 context

You must bind the function to outer context

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

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

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

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