2017-05-08 27 views
2

當我嘗試讀取套接字回調函數內我的道具,它拋出一個錯誤:如何閱讀socket.io回調中的道具?

componentWillMount(){ 

    console.log(this.props.username); // works 
    this.props.socket.on('question', function(){ 
     console.log(this.props.username); //prints Cannot read property 'username' of undefined 
     } 
    }); 
    } 

我怎樣才能解決這個問題?

回答

1

的問題是,function()呼叫改變的背景和this不再指向組件的實例,因此this.propsundefined。您可以使用arrow function,該arrow functionthis作爲組件的實例。

一個箭頭函數不會創建它自己的這個上下文,所以它有它的原始含義來自封閉的上下文。

componentWillMount() { 
    this.props.socket.on('question',() => { // arrow function 
    console.log(this.props.username); 
    }); 
} 
1

綁定,因爲這樣的插座功能的情況下,你可以從陣營組件的情況下取得的道具,否則thissocket.on功能將參考其自己的上下文,而不是做出反應組件

this.props.socket.on('question', function(){ 
    console.log(this.props.username); 
    }.bind(this) 
}); 

this.props.socket.on('question',() => { 
    console.log(this.props.username); 
    } 
});