我正在尝试做一个连接到 SignalR 集线器并在单击按钮时发送信息的应用程序,但由于某种原因它没有发送任何内容。
const bannerId = 1;
const App = () => {
useEffect(() => {
let newConnection = new HubConnectionBuilder()
.withUrl('https://localhost:7116/bannerHub')
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
if (connection) {
connection.start()
.then(result => {
console.log('Connected!');
})
.catch(e => console.log('Connection failed: ', e));
}
}, [connection]);
const disableBanner = async (evt) => {
await connection.send('DisableBanner', bannerId);
}
const enableBanner = async (evt) => {
await connection.send('EnableBanner', bannerId);
}
return(
<>
<button onClick={async () => { await disableBanner(); }} className='btn btn-primary'>Disable banner</button>
<button onClick={async () => { await enableBanner(); }} className='btn btn-primary'>Enable banner</button>
</>
);
}
我正在使用的包是
@microsoft/signalr
和 connection
对象是 HubConnection
.
有人知道我做错了什么吗?
谢谢,我希望这对遇到同样问题的其他人有所帮助!
我解决了
我的问题出在服务器端。 SignalR 方法等待
string bannerId
,我向他们发送 int
(或 JS 中的 Number
)。我认为数据绑定会解决这个问题,但由于某种原因在这里不起作用。
两种可能的解决方案是:
int bannerId
而不是 string bannerId
bannerId: string
而不是bannerId: number
.就是这样。谢谢大家的评论。