首页 > 解决方案 > React SignalR 回调缺少常量

问题描述

我正在使用带有反应钩子和 SignalR 的 React。我有一些链接到输入字段的 consts 属性

const [name, setEmployeeName] = useState<string>('');
const [id, setEmployeeId] = useState<string>('');
const [project, setProjectName] = useState<string>('');

并按照聊天教程设置连接和订阅 useEffect 之类的

useEffect(() => {

    // Set the initial SignalR Hub Connection.
    const createHubConnection = async () => {

        const hubConnect = new HubConnectionBuilder()
            .withUrl(`${url}/emp`)
            .build()
        try {
            await hubConnect.start()
            console.log('Connection successful!')

            hubConnect.on('update', (employee: Employee) => {
                if(id === employee.id) {
                     setEmployeeName(employee.name)
                     setProjectName(employee.project)
                 }
            })
        }
        catch (err) {
            alert(err);
            console.log(err);
            console.log('Error while establishing connection: ' + { err })
        }
        setHubConnection(hubConnect);
    }

    createHubConnection();

}, [])

因此,当我从服务器端调用“更新”方法并在此处输入实现时,所有这些 const 都丢失并且是“”。

所以这if(id === employee.id)总是错误的。

对我来说,似乎我需要绑定 .this 但我认为我们在 React 中没有这个。

标签: reactjssignalrreact-hooks

解决方案


好的,经过进一步思考,我意识到这不是一个好方法。所以我调整了订阅。将输入更改链接到此方法:

function onIdChange(_id: string) {
    if(_id !== id) {
        hubConnection!.off(`updateEmployee/${id}`)
        setEmployeeId(_id)

        hubConnection!.on(`updateEmployee/${_id}`, (employee: Employee) => {
            setEmployeeName(employee.name)
            setProjectName(employee.project)
        })
    }
}

所以现在从服务器上,每当我想用employeerId调用一个方法时,我已经设置了一个订阅,一旦我调用它,我就不再需要执行if语句。


推荐阅读