如何防止 React Native 中的连接丢失?

How to prevent connection loss in React Native?

在我的 React Native 应用程序中存在用户可能离开该应用程序但随后又返回的实例。而 运行 在 Expo 中,如果用户离开太久,他们将失去与服务器的连接。我怎么能prevent/correct这个?我们正在使用 Websocket

你可以这样实现addEventListener的使用效果

import {AppState} from 'react-native';

useEffect(() => {
  setTimeout(() => {
    AppState.addEventListener("change", _handleAppStateChange);
   }, 2000);
return () => {
  AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);

在这里定义你的_handleAppStateChange

const _handleAppStateChange = (nextAppState) => {
if (
  appState.current.match(/inactive|background/) &&
  nextAppState === "active"
) {
  console.log("App has come to the foreground!");
  //clearInterval when your app has come back to the foreground
  BackgroundTimer.clearInterval(interval)
  
}else{
  //app goes to background
  console.log('app goes to background')
  //tell the server that your app is still online when your app detect that it goes to background
  interval = BackgroundTimer.setInterval(()=>{
  },100)
appState.current = nextAppState;
console.log("AppState", appState.current);
}

}