英文:
SignalR in react-native weird thing happens
问题
这是您提供的代码块的翻译部分:
我们在ReactJS中有一个工作应用程序,其中有一个实时聊天部分,用于不同用户之间的通信。在ReactJS中,我们使用@microsoft/signalR,一切都运行正常。以下是代码块:
```javascript
useEffect(() => {
const ConnectionId = "e48950002479" // user.token;
const newConnection = new HubConnectionBuilder()
.withUrl('https://none_of_your_business/chatHub', {
accessTokenFactory: () => ConnectionId
}) //替换为您的SignalR hub的URL
.configureLogging(LogLevel.Debug)
.build();
setConnection(newConnection);
}, [])
useEffect(() => {
if (connection) {
connection
.start()
.then(() => {
console.log("SignalR Connected!");
connection.on("ReceiveMessage", (message) => {
console.log("Received message:", message);
});
})
.catch((error) => console.log(`SignalR Connection error: ${error}`));
}
}, [connection]);
const sendMessage = async () => {
await connection.invoke('SendMessage', "1626659a57c6", "Heyo", "1626659a57c6");
};
然而,当我在React Native中复制相同的代码(使用相同的库)时,它不会发送ConnectionId变量。这真的很奇怪,因为它在ReactJS中运行良好,但在React Native中不起作用。有什么建议吗?
<details>
<summary>英文:</summary>
We have a working application in ReactJS and there is a part which is a real time chat between different users. In reactJs we used @microsoft/signalR and everything works fine. This is the block of code:
useEffect(() => {
const ConnectionId = "e48950002479" // user.token;
const newConnection = new HubConnectionBuilder()
.withUrl('https://none_of_your_business/chatHub', {
accessTokenFactory: () => ConnectionId
}) //replace with the URL of your SignalR hub
.configureLogging(LogLevel.Debug)
.build();
setConnection(newConnection);
}, [])
useEffect(() => {
if (connection) {
connection
.start()
.then(() => {
console.log("SignalR Connected!");
connection.on("ReceiveMessage", (message) => {
console.log("Received message:", message);
});
})
.catch((error) => console.log(`SignalR Connection error: ${error}`));
}
}, [connection]);
const sendMessage = async () => {
await connection.invoke('SendMessage', "1626659a57c6", "Heyo", "1626659a57c6");
};
however when I copied the same code for react-native (with the same library), the thing does not send the ConnectionId variable. It is really weird because it works flawless in reactJS but not in react-native. Any tips?
</details>
# 答案1
**得分**: 1
已解决方法是更改:
```javascript
useEffect(() => {
const ConnectionId = "e48950002479"; // user.token;
const newConnection = new HubConnectionBuilder()
.withUrl('https://none_of_your_business/chatHub?access_token=' + ConnectionId) // 替换为您的 SignalR hub 的 URL
.configureLogging(LogLevel.Debug)
.build();
setConnection(newConnection);
}, [])
英文:
Solved it by changing:
useEffect(() => {
const ConnectionId = "e48950002479" // user.token;
const newConnection = new HubConnectionBuilder()
.withUrl('https://none_of_your_business/chatHub?access_token=' + ConnectionId) //replace with the URL of your SignalR hub
.configureLogging(LogLevel.Debug)
.build();
setConnection(newConnection);
}, [])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论