2016-09-20 45 views
0

我有一个类应用中反应绑定托座延伸反应组件

class App extends Component 

componentWillMount()我初始化插座this.socket = io();。 现在如果我用插座componentWillMount外面我收到一个错误的另一个功能,例如anotherfunction(){ this.socket.emit('welc_message','hello'); }

我收到

Uncaught TypeError: Cannot read property 'emit' of undefined

+0

我试过'this.anotherfunction.bind(this);'在componentWillMount。并发生相同的错误。 – abderrahmen

+0

你能展示更多的代码吗?也许,因为你正在做一些异步任务“IO()”,因此您需要处理this.socket的初始化时IO完成,然后调用的setState重新渲染 –

+1

我只是试着VAR应用=阵营.createClass而不是扩展组件和它的作品所以最有可能它是有约束力的问题,因为延长零部件的doesen't做自动绑定 – abderrahmen

回答

1

的解决方案是在构造函数中的一部分,我们结合anotherfunction的背景,所以我们做的通过this.anotherfunction = this.anotherfunction.bind(this) 这里是如何整个应用程序文件夹看起来像App.js