reactjs - 如何读取 socket.io 回调中的 props?

标签 reactjs socket.io

当我尝试在套接字回调函数中读取我的 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/

相关文章:

javascript - react : Update className of this. props.children

javascript - Websockets 和二进制数据

go - 通过 go-socked.io 接收字节数组时出错

javascript - 如何与多个客户端实时共享表单输入值?

node.js - NodeJS 和 Socket.IO 来跟踪用户访问时间 高性能

reactjs - Webpack - 未捕获的 TypeError : (0 , _reactDom2.default) 不是函数

asynchronous - Flux:如何处理多个异步请求

reactjs - Reactfire,mixin 不是被弃用了吗?

javascript - React JS 如何重置表单

go - Socket.io 客户端无法与 websocket 服务器一起使用