如何在导航到不同屏幕时断开socket连接

5

我正在使用socket.io-client获取加密货币最新数据

constructor() {
    super();
      this.socket = openSocket('https://coincap.io');
    }

然后在componentDidMount中调用它。

 componentDidMount() {
    this.socket.on('trades', (tradeMsg) => {
          for (let i=0; i< this.updateCoinData.length; i++) {
             console.log("it is being called still")
              if (this.updateCoinData[i]["short"] == tradeMsg.coin ) {
                  this.updateCoinData[i]["price"] = tradeMsg["message"]['msg']['price']
                  //Update the crypto Value state in Redux
                  this.props.updateCrypto(this.updateCoinData);
              }
          }
      })

由于套接字已经开启,它会持续发出消息。现在我认为当我从一个屏幕导航到另一个屏幕时,套接字连接将断开,因此我正在做类似这样的操作。

componentWillUnmount() {
 this.socket.disconnect();
}

虽然我已经跳转到另一个页面,但是我的socket仍在发射信号,这意味着它仍然连接着。

我不确定这是否是因为 react-navigation,但我正在使用StackNavigator

这是我的react-navigation组件:

export const MyScreen = createStackNavigator({
  Home: { 
    screen: CoinCap
  },
  CoinCapCharts: {
     screen: CoinCapCharts
    },
  CurrencySelection: {
    screen: CurrencySelection
  },
  CoinChart: {
    screen: CoinChart
  },
  News: {
    screen: News
  }

},{
    initialRouteName: 'Home',
    headerMode: 'none'
});

问题:当用户从一个屏幕导航到另一个屏幕时,如何关闭套接字?并在用户导航回到相同的屏幕时重新打开它?


执行 socket.close() 之前,你可能想要查看一下这个链接 https://github.com/socketio/socket.io-client/blob/master/docs/API.md - Harrison
1个回答

4

解决方案

1. 在调用以下代码的时候,首先尝试断开socket连接。

navigate() {
    this.socket.disconnect();
    this.props.navigation.navigate('CoinCapCharts');
}

2. 使用导航生命周期监听器:文档

  • willFocus - 屏幕将要聚焦
  • willBlur - 屏幕将要失焦
  • didFocus - 屏幕已经聚焦(如果有转换,则转换已完成)
  • didBlur - 屏幕已经失焦(如果有转换,则转换已完成)

componentDidMount() {
  this.didFocusSubscription = this.props.navigation.addListener(
    'willFocus', () => { DO_WHAT_YOU_WANT }
  );
}

componentWillUnmout() {
    this.didFocusSubscription.remove();
}

为什么?

当您导航到屏幕时,特别是在使用 StackNavigation 时,无法保证您的屏幕组件会卸载。因为 StackNavigation 使用推送和弹出来管理屏幕的堆栈,所以在推入另一个屏幕时前一个屏幕不会被卸载。


准确地说,我正在考虑转移到选项卡导航,因为即使我能够断开连接,当用户再次返回屏幕时,我将很难打开socket.on。选项卡视图应该可以解决问题吧? - Alwaysblue
@VarunBindal 我更新了我的答案。使用导航生命周期监听器可能是你的解决方案。 - Jeff Gu Kang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接