在导航器中调用的导航器的反应原生问题
问题描述:
我是反应原生和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))
}
导航总是未定义所有这些功能(除了最初的按钮单击事件)是父组件
答
为此找到了一个解决方案,看起来像一个函数作为参考传递时,全局常量是不可用的,即使该函数是在声明的常量的同一个文件中产生的,'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中使用,并按预期工作。
我做了一个快速的研究。看起来导航器是由react-native定义的全局定义。这些全局变量用于在不导入的情况下使通用函数可达。例如,您可以直接使用fetch()而不导入它,因为它已被绑定。检查下面的文档https://github.com/facebook/react-native/blob/4252ac75eaf04aa9d57027e91bf7665717ed4eab/Libraries/Core/InitializeCore.js它解释了很多。 –
@BurakKarasoy是的,我当然明白。第一个函数调用按预期工作。但全局范围在第二次函数调用后不可用。就好像环境是孤立的。不知道在哪里或如何。我不介意传递给导航员,但是,所有的尝试都失败了。寻找一些指导。 – thun