在我的 React Native 应用程序中有一些实例,用户可能会离开应用程序,然后又回来。在 Expo 中运行时,如果用户离开时间过长,他们将失去与服务器的连接。我该如何预防/纠正这种情况?我们正在使用 Websocket
答案 0 :(得分:1)
你可以像这样在使用效果中实现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);
}
}