javascript - 无法读取 AJAX 调用中未定义的属性 'setState'

标签 javascript jquery ajax reactjs jsonp

我正在尝试从 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)到外部上下文

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/

相关文章:

javascript - 如何将数据标签与数据一起传递以在 Highcharts 的工具提示中显示它

javascript - 使用 ID 从 Google 表格中查找正确的值 - 避免多个 "else if" block - 构建数组

javascript - Vue组件中继承CSS

javascript - 按钮需要多次点击才能更改 : jQuery

javascript - Ajax 在 IE 8/9 中提取缓存页面,但在 FF 中工作正常

javascript - Qualtrics Javascript 键盘按下

json - Instagram 的最大请求数是多少?

javascript不想解析文本超过两次

javascript - IE11 HTTPS AJAX XMLHttpRequest : Network Error 0x2eff, 由于错误 00002eff,无法完成操作

javascript - AJAX 中的数组请求 JSON 对象数据