gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:38:31 25 4
gpt4 key购买 nike

我在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com