如何在 Signalr connection.on() 中设置组件状态

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

我想用信号器从服务器获取数据并更新 React 组件的内容。一切都好。从服务器接收到数据,但组件状态无法更新(未定义)。

这是我的代码:

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());
        });


    }

setState 是一个函数,所以

this.setState = ({ message: msg })

应该是

this.setState({ message: msg })

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

notifConn.on("ReceiveMessage", (msg) => {
   this.setState({ message: msg })
});

你能这样写你的构造函数吗:

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

}

并使用它来改变状态:this.setState({message:msg})

你应该这样做...

this.setState({ message: msg })

setState 是一个函数,它修改组件变量的当前状态并强制组件重新渲染结果。 虽然你可以这样做(强烈不推荐

this.state.message = msg; 

但这不会通知组件重新渲染。