该应用程序是一个测验,如果用户完成了回合,他可以将分数发送到火力地堡。如果用户未连接到Internet,则将这些点保存在设备内存中,因此,建立连接后,这些点将在firebase中发送。
最好是让这种情况自动发生并显示一条消息...
我正在尝试在App.js
的{{1}}中执行此操作,但是它仅在我刷新该应用程序时检查。我尝试了useEffect
和withNavigationFocus
,但错误:useFocusEffect
。
如果建立连接以添加点,我还可以将代码移至the App.js is unable to get access to navigation...
并显示一个按钮,但这不是那么用户友好。
任何想法都会受到赞赏。
谢谢!
WelcomeScreen.js
解决方案
WelcomeScreen.js
useEffect(() => {
const getPoints = async () => {
let points = await AsyncStorage.getItem("savedPoints");
if (!!points) {
const getEmail = async () => {
const userData = await AsyncStorage.getItem("userData");
if (userData) {
const transformedData = JSON.parse(userData);
const { userEmail } = transformedData;
return userEmail;
}
};
const email = await getEmail();
// Give it some time to get the token and userId,
// because saveData needs them.
setTimeout(
async () => await dispatch(dataActions.saveData(email, +points)),
3000
);
await AsyncStorage.removeItem("savedPoints");
}
};
NetInfo.fetch().then(state => {
if (state.isConnected) {
console.log("isConnected");
getPoints();
}
});
}, []);
答案 0 :(得分:1)
您可以设置一个侦听器以侦听Internet连接。不要在app.js中使用任何逻辑,请在单独的屏幕组件中使用它。
constructor(props) {
super(props);
this.state = {
isConnected: false
};
}
componentDidMount() {
this.listenForInternetConnection = NetInfo.addEventListener(state => {
// your logic is here or setState
this.setState({
isConnected: state.isConnected
});
});
}
componentWillUnmount() {
this.listenForInternetConnection();
}
答案 1 :(得分:-1)
您可以使用JS EventListeners
window.addEventListener('load', () => {
navigator.onLine ? showStatus(true) : showStatus(false);
window.addEventListener('online', () => {
showStatus(true);
});
window.addEventListener('offline', () => {
showStatus(false);
});
});