javascript - 在 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);
不幸的是没有运气...
解决方案
你试过了吗
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);
}
};
推荐阅读
- group-by - 在 Neo4j 中,如何按一个返回键分组,而不是所有非聚合键作为返回?
- bash - Sed 替换 - 制表符空格
- validation - Yii2 唯一验证器作为临时验证器
- qt - 如何在 QT 设计器 .ui 文件中链接外部 qss 样式表
- here-api - 如何在 HERE v7 反向地理编码 API 中过滤结果
- wordpress - 如何将 Stripe ApplePay 添加到 woocommerce 迷你购物车
- java - 如何使用 teechart 添加新系列?
- javascript - 我想用 JavaScript 将对象数组转换为对象
- php - 如何在 php 中使用 for 制作 zig-zag 数字?
- php - 当前行与前一行的 PHP Oracle 减法