首页 > 解决方案 > 在 React.js 中将值从一个函数传递到另一个函数

问题描述

我有 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() 中看到响应,但我得到了

未捕获的 TypeError:this.getLocationName 不是函数

我试着不带“这个”来称呼它。试图像这样在构造函数中绑定它

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

也试过这样称呼它:

() => this.getLocationName(text); 

不幸的是没有运气...

标签: javascriptreactjs

解决方案


你试过了吗

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);
        }
    };

推荐阅读