React SignalR回调缺少常量

问题描述 投票:0回答:1

我正在使用带有React钩子和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();

}, [])

因此,当我从服务器端调用'update'方法并在此处输入实现时,所有那些const都将丢失并且为''。

所以此if(id === employee.id)始终为假。

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

我正在使用带有React钩子和SignalR的React。我有一些consts属性链接到输入字段const [name,setEmployeeName] = useState (''); const [id,setEmployeeId] = ...

reactjs signalr react-hooks
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.