javascript - 反应 this.SetState 未定义 - 嵌套函数
问题描述
制作我的第一个反应应用程序。我想根据用户的位置更新谷歌地图 api。我收到错误“这是未定义的”。我理解使用 .bind(this) 并包装在箭头函数中,但认为这种情况有点不同,因为我在嵌套函数中设置状态:
constructor(props) {
super(props);
this.state = {zip: null, lat: 40.5304 , lng: -100.6534 , zoom: 3.8 };
this.updateCurrentPosition= this.updateCurrentPosition.bind(this);
}
//...
updateCurrentPosition = () => {
navigator.geolocation.getCurrentPosition(success, error);
function success(pos) {
this.setState(`{lat: ${pos.coords.latitude}, lng: ${pos.coords.longitude}, zoom: ${3.8}`)
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
};
}
ops = () => {
return {
center: { lat: this.state.lat, lng: this.state.lng },
zoom: this.state.zoom
}
};
解决方案
箭头函数自动将函数绑定到父类。如果一个函数没有绑定,或者不是箭头函数,“this”将只引用函数本身,即使它是嵌套的。您的成功函数(以及失败函数)未绑定到父类,因为您既没有绑定它也没有将其定义为箭头函数。
推荐阅读
- javascript - 如何读取 index.html 文件中的 .js 配置文件
- python - Python - 如何从命令打印整个输出?
- windows - 如何在启动程序之前检查 Windows 10 版本?
- maven - Jenkins 为 Sonarqube 扫描阶段分配了 2 个执行器
- javascript - 如何修复类型 '(event: any, el: any) => void' 不可分配给类型 '(arg: { isMirror: boolean; isStart: boolean;
- docker - 我在 docker 容器中有 mongo db,我想连接在另一个容器上运行的应用程序
- javascript - CapacitorJS Plain Javascript - 从相机插件获取视频元素
- reactjs - 如果相关道具未明确设置为未定义,则回调参数类型变为任何
- sql - Sql - 计算库存天数
- swagger - OpenAPI:您可以在示例中使用子组件吗?