我正在使用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