在 React.js 中将值从一个函数传递到另一个函数

时间:2021-03-31 13:19:12

标签: javascript reactjs

我有 2 个函数 getLocation() 和 getLocationName()。

getLocation() 函数执行一个 XMLHttpRequest,我希望将响应传递给 getLocationName() 函数以便在列表中显示它。

getLocationName = (location) => {
    var locName = location;
    console.log("location name", locName)
    return locName;
}

getLocation = (lat, lon) => {
    var text;
    var xmlhttp = new XMLHttpRequest();
    var url = "https://nominatim.openstreetmap.org/search?format=jsonv2&accept-language=sr-Latn&limit=3&q=" + lat + "," + lon;
    console.log("url: ", url)
    xmlhttp.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var resp = JSON.parse(this.responseText);                
            text = resp[0].display_name;
            console.log("response: ", text);
            this.getLocationName(text);
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

我可以在来自 getLocation 的 console.log() 中看到响应,但我得到

<块引用>

未捕获的类型错误:this.getLocationName 不是函数

我尝试在没有“this”的情况下调用它。试图像这样在构造函数中绑定它

constructor(props){
    super(props);
    this.getLocationName = this.getLocationName.bind(this);
}

也试过这样称呼它:

() => this.getLocationName(text); 

不幸的是……

2 个答案:

答案 0 :(得分:0)

你尝试了吗

xmlhttp.onreadystatechange = () => {
        if (this.readyState == 4 && this.status == 200) {
            var resp = JSON.parse(this.responseText);                
            text = resp[0].display_name;
            console.log("response: ", text);
            this.getLocationName(text);
        }
    };

答案 1 :(得分:0)

是的。这是关于“这个”的。 “xmlhttp”对象有它自己的“this”。 试试这个:

getLocation = (lat, lon) => {
    var that = this; //save this
    var text;
    var xmlhttp = new XMLHttpRequest();
    var url = "https://nominatim.openstreetmap.org/search?format=jsonv2&accept-language=sr-Latn&limit=3&q=" + lat + "," + lon;
    console.log("url: ", url)
    xmlhttp.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var resp = JSON.parse(this.responseText);                
            text = resp[0].display_name;
            console.log("response: ", text);
            that.getLocationName(text);
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}