【发布时间】: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'
});
问题:当用户从一个屏幕导航到另一个屏幕时如何关闭套接字?并在用户导航到相同的给定屏幕时重新打开它?
【问题讨论】:
-
做
socket.close()你可能想看看github.com/socketio/socket.io-client/blob/master/docs/API.md
标签: reactjs sockets react-native