How to set state of component in Signalr connection.on()

6 javascript signalr reactjs

I want to get data from server with signalr and update content of React component. Everything is ok. Data is received from the server BUT state of component could not update (undefined).

Here is my code:

import React, { Component } from 'react';
import { ToastComponent } from '@syncfusion/ej2-react-notifications';
import * as signalR from '@aspnet/signalr';


class Notification extends React.Component {

    constructor() {
        super(...arguments);
        this.position = { X: 'Right', Y: 'Top' }
        this.state = { message:null}

    }

    toastCreated() {
        this.toastInstance.show({ timeOut:0 })
    }

    componentWillMount() {
        const notifConn = new signalR.HubConnectionBuilder().withUrl("/notif").build();
        notifConn.on("ReceiveMessage", function (msg) {
            this.setState = ({ message: msg })

        });
        notifConn.start().then(function () {
            notifConn.invoke("SendNotification");

        }).catch(function (er) {
            console.log(er.toString());
        });


    }
Run Code Online (Sandbox Code Playgroud)

Ric*_*pes 4

setState是一个函数,所以

this.setState = ({ message: msg })
Run Code Online (Sandbox Code Playgroud)

应该改为

this.setState({ message: msg })
Run Code Online (Sandbox Code Playgroud)

此外,您的函数将无法访问您的类的this. 因此,您应该使用保留上下文的箭头函数,而不是普通的匿名函数:

notifConn.on("ReceiveMessage", (msg) => {
   this.setState({ message: msg })
});
Run Code Online (Sandbox Code Playgroud)