![](/img/trans.png)
[英]Passing function in React.js from one function component to another
[英]Passing a value from one function to another function in React.js
我有 2 個函數 getLocation() 和 getLocationName()。
getLocation() function 執行 XMLHttpRequest 並且我希望將響應傳遞給 getLocationName() function 以便在列表中顯示它。
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 不是 function
我試着不帶“這個”來稱呼它。 試圖像這樣在構造函數中綁定它
constructor(props){
super(props);
this.getLocationName = this.getLocationName.bind(this);
}
也試過這樣稱呼它:
() => this.getLocationName(text);
不幸的是沒有運氣...
你試過了嗎
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);
}
};
是的。 這是關於“這個”的。 “xmlhttp” object 有自己的“這個”。 嘗試這個:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.