reactjs - React Navigation 6: Ta bort skärm som förhindras av `beforeRemove`-lyssnare
Jag är ny med React Navigation 6.
Jag har en skärm med en beforeRemove-lyssnare med en dialog för att be användaren att avsluta vid bekräftelse.
Mitt problem är att ta bort skärmen som förhindras av beforeRemove-lyssnaren. Jag använde e.data.action för att avsluta och det fungerar i tid, men ibland vill jag avsluta skärmen direkt utan bekräftelse. e.data.action kommer att tillhandahållas när beforeRemove triggas.
Jag googlade på många ämnen men fick inget, inte ens på den officiella React Navigation 6.x-dokumentationen
Här är min kod:
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();
});
Svar #1
Du kan välja BackHandler istället för att använda beforeRemove, eftersom beforeRemove kommer att anropas oavsett vad när du lämnar skärmen, men BackHandler hanterar exakt bara tillbaka-knappen, se hur..
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();
}, []);
Skål.
