【问题标题】:Cannot read property 'setState' of undefined in AJAX call无法读取 AJAX 调用中未定义的属性“setState”
【发布时间】:2016-12-19 13:18:38
【问题描述】:

我正在尝试从 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 不支持它。

【问题讨论】:

  • 您可以发布示例响应吗?
  • this in setWeatherData 不会是您想象的那样 - 您需要显示更多上下文以便我们提供帮助,因为无法确定 this 应该是什么跨度>

标签: javascript jquery ajax reactjs jsonp


【解决方案1】:

你必须将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)
        }
    });
}

【讨论】:

  • 我是个白痴。我试图从 json 访问错误的孩子。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2019-04-09
  • 2019-12-30
  • 2017-05-30
  • 2018-12-16
  • 2018-12-05
  • 2016-03-03
相关资源
最近更新 更多