【发布时间】:2017-01-28 17:17:37
【问题描述】:
我在 react 中有一个类 App
class App extends Component
在componentWillMount() 中,我已经初始化了套接字this.socket = io();。
现在,如果我在 componentWillMount 之外的另一个函数中使用套接字,我会收到一个错误,例如 anotherfunction(){
this.socket.emit('welc_message','hello');
}
我收到了
未捕获的类型错误:无法读取未定义的属性“发射”
【问题讨论】:
-
我在 componentWillMount 中尝试过
this.anotherfunction.bind(this);。并发生同样的错误。 -
你能展示更多你的代码吗?可能是因为您在 'io()' 中执行了一些异步任务,因此您需要在 IO 完成时处理 this.socket 的初始化,然后调用 setState 重新渲染
-
我刚刚尝试了 var App = React.createClass 而不是 extends 组件,它的工作原理很可能是绑定问题,因为扩展组件不进行自动绑定
-
您也可以在组件之外完全定义套接字,然后它将在文件中的任何位置可用,这样您就不会在每次安装组件时都重新连接
-
@azium 同样的事情没有结果。但是当我在 componentWillMount 中执行 console.log (this) 时,我得到了包含 socket 的 App 对象。而当我在另一个函数中执行 console.log(this) 时,我没有得到 App 函数,但本地对象也 console.log(this.socket) 返回 undefined
标签: javascript reactjs socket.io