Cannot read property 'setState' of undefined in AJAX call

前端 未结 1 1194
不知归路
不知归路 2021-01-21 16:46

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

相关标签:
1条回答
  • 2021-01-21 17:20

    You must bind the function to outer 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)
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题