javascript - React.js 组件中 websocket 的 onopen 事件中调用函数

标签 javascript reactjs websocket

我在React.js组件中使用websocket,并尝试在websocket的onopen事件中调用本地方法registerconsole.log() 在 onopen 事件中工作正常,但我的本地函数 register 却不行。我收到错误注册不是函数

这是代码

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}

任何帮助!

最佳答案

那是因为 this 的值正在改变。发生的情况是,您将一个函数分配给 this.ws.onopen,然后 Web 套接字实例调用 onopen,其中 this 指向Web套接字本身,而不是你的reactjs类实例。您需要保留对reactjs类实例的引用并使用它来调用register方法:

this.ws.onopen = () =>
{
  console.log('Connected! now registering');
  this.register();
}

上面使用箭头函数(ECMA6 功能)来保留 this 的值。这是可行的,因为箭头函数不允许其调用者(在本例中为 Web 套接字)更改其 this 值。或者你可以这样做:

var self = this;
this.ws.onopen = function()
{
  console.log('Connected! now registering');
  self.register();
}

它只是在执行函数之前存储对reactjs对象的引用,其中this的值发生了变化。或者你可以这样做:

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}.bind(this)

在将函数分配给属性 this.ws.onopen 之前,断言无论是谁或如何调用该函数,this 的值函数将始终是您传递给 .bind 的任何内容。

关于javascript - React.js 组件中 websocket 的 onopen 事件中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072078/

相关文章:

javascript - 为什么这段 JavaScript 代码没有执行?

javascript - 根据权限名称过滤用户

javascript - 无法实现身份验证路由

java - 如何保证websocket消息的可靠传递?

javascript - jquery 在 <ul> 中显示项目列表

javascript - 即使没有选择任何单选按钮,Radiobutton .val()也不返回空值

google-chrome - 跨域 websocket 连接在 chrome 中失败,在 firefox 中工作

javascript - SignalR - 从没有 SignalR 库的 javascript 连接到 websocket 服务

reactjs - 找不到 typescript 模块无法解决

javascript - 在同一设备 reactJS 上登录时跨配置文件保留的信息