2016-09-20 49 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