【发布时间】:2017-02-11 18:48:34
【问题描述】:
我是 react-native 和 ES6 的新手。我在“父”组件中有所有状态。用户单击“子”组件中的按钮。然后它获取他们的 GPS 位置(一个功能),通过 AJAX 发布结果(另一个功能),最后重定向到成功页面。 Child 在此处加载了导航器调用:
<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) )
}
navigator 始终未定义。所有这些功能(除了初始按钮单击事件)都是父组件。
【问题讨论】:
-
我做了一个快速的研究。看来 navigator 是 react-native 定义的全局定义。这些全局变量用于使常用函数无需导入即可访问。例如,您可以直接使用 fetch() 而无需导入它,因为它已经绑定。查看github.com/facebook/react-native/blob/…下面的文档,它解释了很多。
-
@BurakKarasoy 是的,我明白。第一个函数调用按预期工作。但是在第二次函数调用后全局范围不可用。就好像环境是孤立的。不确定在哪里或如何。我不介意传入对导航器的引用,但是,所有尝试都失败了。寻求一些指导。
标签: reactjs react-native