I am new with React Navigation 6.
I have a screen with beforeRemove
listener with a dialog to ask user to exit on confirmation.
My problem is the removing screen which prevented by beforeRemove
listener.
I used e.data.action
to exit and its works on time but sometimes i want to exit screen directly wihtout confirmation. e.data.action
will provided when beforeRemove
triggered.
I googled a lot subjects but got nothing, even on official React Navigation 6.x documentation
Here is my code:
useFocusEffect(() => {
const callback = e => {
setActionForLater(e.data.action) // <- i used a helper variable, i dont know it helps or not, because it works after `beforeRemove` listener triggered
e.preventDefault();
const exitDialog = Dialog.show({
title: 'Exit',
subtitle: 'Do you want to exit without save?',
buttons: [
{
title: 'Exit',
textStyle: { color: '#f44' },
onPress: () => {
props.navigation.dispatch(e.data.action);
},
},
{
title: 'Cancel',
onPress: () => {
Dialog.hide(exitDialog);
},
},
],
});
}
};
const unsubscribe = navigation.addListener('beforeRemove', callback);
return () => unsubscribe();
});
CodePudding user response:
You may choose BackHandler
, rather than using beforeRemove
, because beforeRemove will get called no matter what when leaving the screen, but BackHandler will exactly handle only the back button, see how..
import {BackHandler} from "react-native"
useEffect(() => {
const callback = () => {
Dialog.show({
title: 'Exit',
subtitle: 'Do you want to exit without save?',
buttons: [
{
title: 'Exit',
textStyle: { color: '#f44' },
onPress: () => {
props.navigation.dispatch(e.data.action);
},
},
{
title: 'Cancel',
onPress: () => {
Dialog.hide(exitDialog);
},
},
],
});
return true;
};
const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
callback
);
return () => backHandler.remove();
}, []);
Cheers.