2017-02-11 116 views
1

我是反應原生和ES6的新手。我已經在「父」組件中聲明。用戶點擊「兒童」組件中的按鈕。然後抓取他們的GPS位置(一個函數),通過AJAX(另一個函數)發佈結果,最後重定向到成功頁面。孩子是裝載了導航來電來訪:在導航器中調用的導航器的反應原生問題

<ChildComponent btnClick={this._getGps.bind(this)} /> 

以上工作正常並且父組件的樣子:

_getGps() { 
    navigator.geolocation.getCurrentPosition(
     (position) => { 
     this._postResults(position) 
     }, 
     (error) => { 
     console.log(error) 
     }, 
     {enableHighAccuracy: true, timeout: 2500, maximumAge: 10000} 
    ) 
} 

上面也按預期工作。然後它調用_postResults,它會產生一個.fetch請求。也工作正常,並返回一個有效的迴應。問題是從響應函數中訪問導航器對象。我找不到範圍(我曾嘗試navigator.replace和this.navigator.replace:。

_postResults(position) { 
    fetch('https://my.rest/api', { 
    method: 'POST', 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json', 
    }, 
    body: JSON.stringify(position) 
    }).then((response) => response.json()) 
    .then((responseJson) => { 
     // this works fine 
     this.setState({position:position}) 
     // here is the problem 
     navigator.replace({ 
     id: 'SomeOtherComponent' 
     }) 
    }) 
    .catch((error) => console.log(error)) 
} 

導航總是未定義所有這些功能(除了最初的按鈕單擊事件)是父組件

+0

我做了一個快速的研究。看起來導航器是由react-native定義的全局定義。這些全局變量用於在不導入的情況下使通用函數可達。例如,您可以直接使用fetch()而不導入它,因爲它已被綁定。檢查下面的文檔https://github.com/facebook/react-native/blob/4252ac75eaf04aa9d57027e91bf7665717ed4eab/Libraries/Core/InitializeCore.js它解釋了很多。 –

+0

@BurakKarasoy是的,我當然明白。第一個函數調用按預期工作。但全局範圍在第二次函數調用後不可用。就好像環境是孤立的。不知道在哪裏或如何。我不介意傳遞給導航員,但是,所有的嘗試都失敗了。尋找一些指導。 – thun

回答

0

爲此找到了一個解決方案,看起來像一個函數作爲參考傳遞時,全局常量是不可用的,即使該函數是在聲明的常量的同一個文件中產生的,'this'指的是Component對象。 parent,當我包含ChildComponent時,我通過bind綁定導航器對象:

<ChildComponent btnClick={this._getGps.bind(this, navigator)} 
    navigator={navigator} /> 

當我調用父_getGps函數從ChildComponent導航器被自動經由n變量(其隨後被傳遞到_postResults傳遞:

_getGps(n) { 
    navigator.geolocation.getCurrentPosition(
     (position) => { 
     this._postResults(n,position) 
     }, 
     (error) => { 
     console.log(error) 
     }, 
     {enableHighAccuracy: true, timeout: 2500, maximumAge: 10000} 
    ) 
} 

最後這裏是從_postResults一個片段:

_postResults(n, position) { 
... 

n(導航器)現在可在_postResults中使用,並按預期工作。