导航到其他屏幕时如何断开插座

时间:2018-10-01 23:35:00

标签: reactjs sockets react-native

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

问题:当用户从一个屏幕导航到另一个屏幕时,如何关闭插座?并在用户导航到相同的赠送屏幕时将其重新打开?

1 个答案:

答案 0 :(得分: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时,不能保证屏幕组件的数量。因为StackNavigation使用push和pop来显示屏幕的堆栈,并且在推入另一个屏幕时不会卸载前一个屏幕。