我正在使用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'
});
问题:当用户从一个屏幕导航到另一个屏幕时,如何关闭插座?并在用户导航到相同的赠送屏幕时将其重新打开?
答案 0 :(得分:1)
navigate
时先尝试断开套接字。navigate() {
this.socket.disconnect();
this.props.navigation.navigate('CoinCapCharts');
}
componentDidMount() {
this.didFocusSubscription = this.props.navigation.addListener(
'willFocus', () => { DO_WHAT_YOU_WANT }
);
}
componentWillUnmout() {
this.didFocusSubscription.remove();
}
在浏览屏幕时,尤其是在使用StackNavigation
时,不能保证屏幕组件的数量。因为StackNavigation
使用push和pop来显示屏幕的堆栈,并且在推入另一个屏幕时不会卸载前一个屏幕。