当前位置: 代码迷 >> JavaScript >> 反应this.SetState未定义-嵌套函数
  详细解决方案

反应this.SetState未定义-嵌套函数

热度:64   发布时间:2023-06-03 17:48:29.0

制作我的第一个React应用。 我想根据用户的位置更新Google Maps 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的严格模式下this是未定义的。 您可以参考本段以了解更多信息

对于您的特定问题,当您定义successerror ,这两个功能并不绑定到父项。

通过将功能定义为箭头功能进行以下修改将解决您的问题。

const success = (pos) => {
    this.setState(`{lat: ${pos.coords.latitude}, lng: ${pos.coords.longitude}, zoom: ${3.8}`)
}

const error = (err) => {
    console.warn(`ERROR(${err.code}): ${err.message}`);
}; 

因此,我改为直接将函数作为参数传递给getCurrentPosition方法,它似乎可以正常工作。

 updateCurrentPosition = () => { navigator.geolocation.getCurrentPosition( (pos) => { this.setState({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: 1 }) }, (err) => { console.warn(`ERROR(${err.code}): ${err.message}`) } ) }