当我尝试在套接字回调函数中读取我的 props 时,它会抛出一个错误:
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
}
});
}
我该如何解决这个问题?
最佳答案
问题是 function()
调用更改了上下文,并且 this
不再指向组件的实例,因此 this.props
是未定义
。您可以使用arrow function其中 this
作为组件的实例。
An arrow function does not create its own this context, so this has its original meaning from the enclosing context.
componentWillMount() {
this.props.socket.on('question', () => { // arrow function
console.log(this.props.username);
});
}
关于reactjs - 如何读取 socket.io 回调中的 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43850216/