【问题标题】:How to disconnect socket when navigating to different screen导航到不同屏幕时如何断开套接字
【发布时间】:2019-03-07 02:24:24
【问题描述】:

我正在使用 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();
}

但即使我已经导航到不同的页面,我的套接字仍在继续发出信号,这意味着它仍然处于连接状态。

我不确定这是不是因为 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'
});

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

【问题讨论】:

标签: reactjs sockets react-native


【解决方案1】:

解决方案

1。当您调用navigate 时,请先尝试断开套接字,如下所示。

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

2。使用导航生命周期监听器:doc

  • willFocus - 屏幕将聚焦
  • willBlur - 屏幕将失去焦点
  • didFocus - 屏幕聚焦(如果有过渡,则过渡完成)
  • didBlur - 屏幕失焦(如果有过渡,则过渡完成)

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

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

为什么?

当您浏览屏幕时,尤其是在使用StackNavigation 时,不能保证您的屏幕组件的 ummount。因为StackNavigation 对屏幕的堆栈使用推送和弹出,并且在推送另一个屏幕时不会卸载前一个屏幕。

【讨论】:

  • 确切地说,我正在考虑转到 Tab 的导航,因为即使我能够断开连接,当用户再次返回屏幕时,我也很难打开 socket.on。标签视图应该可以解决问题吗?
  • @VarunBindal 我更新了我的答案。使用导航生命周期侦听器可能是您的解决方案。
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多