gpt4 book ai didi

node.js - Reactjs 无法建立套接字连接,它在调用 componentDidMount 时打开并获取响应

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:57 26 4
gpt4 key购买 nike

我无法在 React.js 中打开 Web 套接字连接。在调用 componentDidMount 中的相同函数时建立连接。当我开始使用 onClick 或 onSubmit 等事件进行调用时,我无法打开连接并从服务器获取响应。

代码如下。

var exampleSocket = new WebSocket('wss://api.somedomain.io/WSGateway');

class MyClass extends Component {
componentDidMount() {
this.authenticate();
}
authenticate() {
exampleSocket.onopen = function (event) {
var payload = {
"UserName": "username",
"Password": "password"
};
var msg = {
"m": 0,
"i": 0,
"n": "AuthenticateUser",
"o": JSON.stringify(payload)
};
exampleSocket.send(JSON.stringify(msg));
}
exampleSocket.onmessage = function apiAuthenticateUser(event) {
try {
let data = JSON.parse(event.data);
let o_data = JSON.parse(data["o"]);
console.log(o_data);
} catch (err) {
console.log(err);
}
}
}
render() {
const { classes, theme } = this.props;
return (
<React.Fragment>
<button
name="authentication"
id="testid1"
onClick={(e) => {
this.authenticate(e);
}}
>
Login
</button>
</React.Fragment>
)
}
}
export default MyClass;

最佳答案

恐怕您的authenticate方法未绑定(bind)到组件的范围。在构造函数中使用绑定(bind)或在声明中使用箭头函数:

class MyClass extends Component {
componentDidMount() {
this.authenticate();
}

authenticate = () => {
exampl...

在 onClick 中只需使用以下格式:

     <button
...
onClick={this.authenticate}
>

关于node.js - Reactjs 无法建立套接字连接,它在调用 componentDidMount 时打开并获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54238898/

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