【发布时间】: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