【问题标题】:react-native issue with navigator invoked within navigator在导航器中调用导航器的反应原生问题
【发布时间】: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


【解决方案1】:

为此找到了解决方案。当函数作为引用传递时,看起来全局常量不可用,即使该函数源自声明的常量所在的同一文件。 'this' 指的是 Component 对象。从父级开始,当我包含 ChildComponent 时,我通过绑定传递导航器对象:

<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 的 sn-p:

_postResults(n, position) {
...

n(导航器)现在可以在 _postResults 中使用,并且可以按预期工作。

【讨论】:

    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    相关资源
    最近更新 更多