reactjs SignalR in react-native奇怪的事情发生了

3lxsmp7m  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(120)

我们在ReactJS中有一个工作应用程序,其中有一部分是不同用户之间的真实的聊天。在reactJs中,我们使用@microsoft/signalR,一切正常。这是代码块:

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");
  };

然而,当我为react-native复制相同的代码时(使用相同的库),它并没有发送ConnectionId变量。这真的很奇怪,因为它在reactJS中工作得很完美,但在react-native中却没有。有什么提示吗?

ymdaylpp

ymdaylpp1#

通过更改解决了它:

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);
  }, [])

相关问题