簡體   English   中英

反應this.SetState未定義-嵌套函數

[英]React this.SetState is undefined - nested function

制作我的第一個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是未定義的。 您可以參考本段以了解更多信息http://2ality.com/2014/05/this.html

對於您的特定問題,當您定義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}`) } ) } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM