简体   繁体   English

使用WebSocket接收消息时如何更改componentDidMount()内部的状态?

[英]How to change state inside componentDidMount() when recieving a message with websockets?

I'm recieving a websocket message. 我收到一个websocket消息。 I want to change the state of my component with this message. 我想用此消息更改组件的状态。 When I try to do this, I get an error. 当我尝试执行此操作时,出现错误。 How do I solve this? 我该如何解决?

componentDidMount() {

    this.wsConnection.onmessage = function (eventInfo) {

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

My error: 我的错误:

TypeError: this.setState is not a function

Can you try the following code 你可以尝试以下代码

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM