【问题标题】:Passing Sockets Through Navigator in React Native在 React Native 中通过 Navigator 传递套接字
【发布时间】:2016-06-23 00:13:15
【问题描述】:

我不断收到undefined is not an object (evaluating this.props.socket.on)。我在index.ios.js 文件中声明我的套接字,如下所示:

class Main extends Component {
   constructor(props) {
      super(props);

      this.state = {
        message: ''
      };
      this.socket = io('http://localhost:8000', {jsonp: false})
 }

然后,在我的renderScene(route, navigator) 导航方法中,我有:

renderScene(route, navigator) {
   if (route.id == 'EnterName') {
     return <EnterName socket={this.socket} navigator={navigator} />
   }
}

render() {
  return (
    <Navigator
       initialRoute={{id: 'EnterName', index: 0}}
      renderScene={ this.renderScene } />
  );
}

但是这个套接字信息没有被正确地传递到 EnterName。尝试时出现上述错误:

this.props.socket.on('chat message', (msg) => {
   this.state.messages.push(msg);
   this.forceUpdate();
});`

你知道为什么套接字没有被正确初始化/传递吗?

【问题讨论】:

  • 我觉得this.renderScene应该是this.renderScene.bind(this)
  • 那会做什么?你能帮我慢慢分解吗?
  • 它与javascript中'this'的范围有关。函数内部的“this”指的是函数本身,但要访问 renderScene 函数内部的主组件的属性,“this”应该指的是主组件。当您使用 bind 时,它会创建一个新函数并将其 this 值设置为提供的值,这里我们在绑定时提供对 (this) 主组件的引用。在这里查看更多。 developer.mozilla.org/en/docs/Web/JavaScript/Reference/….
  • Continuing... 这是一个经典的 javascript 新手陷阱。每个人都会经历这个。也看看这篇文章。 javascriptissexy.com/… 。 G. Hamaide 建议的是在 ES6 版本的 javascript 中引入的编写函数的新语法。它被称为箭头函数。更多信息请访问developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

标签: javascript sockets reactjs components react-native


【解决方案1】:

我认为这是一个上下文问题。您应该使用 es6 粗箭头指定您的渲染方法:

renderScene = (route, navigator) => {
   if (route.id == 'EnterName') {
     return <EnterName socket={this.socket} navigator={navigator} />
   }
}

【讨论】:

  • 你有时间深入解释一下这个箭头方法和上下文问题吗?一位朋友建议我完全放弃 Navigator 以支持 Ex-Nacigator,并且我也使用 Flux。您能谈谈这样做的利弊吗?
【解决方案2】:

看看这个。

这是 gr3x 顺便说一句。

如果您在 renderScene 开始时扔一个 debugger 并检查 this 您会发现您处于不同的范围内, Navigator 的范围,并且您无权访问 Main 中存在的 this.socket,因此您正在传递 undefined 到 EnterName 作为 socket 属性,以及为什么在从 EnterName

访问它时会收到这些错误

相反,将 this.socket 添加到 initialRoute 对象,并通过 routerenderScene 中访问它像这样

renderScene(route, navigator) {
    if (route.id == 'EnterName') {
     return <EnterName socket={route.socket} navigator={navigator} />
    }
}

render() {
  return (
    <Navigator
       initialRoute={{id: 'EnterName', index: 0, socket: this.socket}}
       renderScene={ this.renderScene } />
  );
}

这应该可以解决您的问题。如果我能提供进一步的帮助,请在 reddit 上告诉我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2021-03-08
    • 2015-12-30
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多