在导航器中调用的导航器的反应原生问题



我是 react-native 和 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}
    )
}

以上也按预期工作。然后,它会调用发出 .fetch 请求的_postResults。也可以正常工作并返回有效的响应。问题是从响应函数中访问导航器对象。我找不到范围(我尝试过navigator.replace and 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"是指组件对象。从父级开始,当我包含子组件时,我通过绑定传递导航器对象:

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

当我从 ChildComponent 调用父_getGps函数时,导航器通过 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 中可用,并按预期工作。

最新更新