Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当接收带有WebSocket的消息时,如何更改componentDidMount()内的状态?_Javascript_Reactjs_Websocket - Fatal编程技术网

Javascript 当接收带有WebSocket的消息时,如何更改componentDidMount()内的状态?

Javascript 当接收带有WebSocket的消息时,如何更改componentDidMount()内的状态?,javascript,reactjs,websocket,Javascript,Reactjs,Websocket,我收到一条websocket消息。我想用此消息更改组件的状态。当我尝试这样做时,我得到了一个错误。我如何解决这个问题 componentDidMount() { this.wsConnection.onmessage = function (eventInfo) { console.log("Message arrived from websocket: ", eventInfo.data); this.setState({team: eventInf

我收到一条websocket消息。我想用此消息更改组件的状态。当我尝试这样做时,我得到了一个错误。我如何解决这个问题

componentDidMount() {

    this.wsConnection.onmessage = function (eventInfo) {

        console.log("Message arrived from websocket: ", eventInfo.data);
        this.setState({team: eventInfo.data});
    };
}
我的错误:

TypeError: this.setState is not a function

你能试试下面的代码吗

this.wsConnection.onmessage = (eventInfo) => {

    console.log("Message arrived from websocket: ", eventInfo.data);
    this.setState({team: eventInfo.data});
};

你能试试下面的代码吗

this.wsConnection.onmessage = (eventInfo) => {

    console.log("Message arrived from websocket: ", eventInfo.data);
    this.setState({team: eventInfo.data});
};

通过使用
函数
关键字创建函数,您更改了
。通过使用
函数
关键字创建函数,您更改了
。此操作有效!你能解释一下你的代码和我的代码之间的区别吗?我不太明白发生了什么。有两种实现函数的方法。一个是:
函数func(var0){}
,另一个是:
(var0)=>{}
。在每种类型中,函数引用的范围是不同的。这是关于“JS闭包”的概念。你可以通过这个链接获得更多关于这个的信息!你能解释一下你的代码和我的代码之间的区别吗?我不太明白发生了什么。有两种实现函数的方法。一个是:
函数func(var0){}
,另一个是:
(var0)=>{}
。在每种类型中,函数引用的范围是不同的。这是关于“JS闭包”的概念。您可以通过此链接获得更多信息