reactjs - 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 中没有这个。
解决方案
好的,经过进一步思考,我意识到这不是一个好方法。所以我调整了订阅。将输入更改链接到此方法:
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语句。
推荐阅读
- javascript - 为什么 onclick 事件在触摸屏上不起作用,而在桌面上起作用?
- cluster-analysis - 从一组文档中提取重要的子部分以及与它们相关联的子文档集
- ionic-framework - menuClose 没有关闭我的左侧菜单
- notepad++ - 查找并替换为两个(有些)不相关的随机变量
- angular - 似乎别名“as”不再适用于构建角度
- javascript - 未捕获的 ReferenceError:未定义响应
- ruby-on-rails - 反应本机应用程序身份验证插件网络错误
- reactjs - 在反应中显示/隐藏某些路线的导航组件
- javascript - 如何在具有更多参数的函数中使用 e.preventDefault()?
- python - 如何在 Python 中实现以下 C 代码?(typedef、枚举和开关)