我正在使用 react-navigation 中的 defaultGetStateForAction 来拦截我的导航,这样我就可以提醒我的用户有未保存的数据,并让他选择继续导航并删除未保存的数据或先保存它。此数据存储在更高的组件状态中,可以通过 screenProps 可用的函数访问该状态
所以......这是我的代码:
const CreateAnimalStack = createStackNavigator({
CreateAnimal: { screen: createAnimalScreen },
ListAnimals: { screen: listAnimalsScreen },
DetailAnimal: { screen: detailAnimalScreen },
ReviewAnimal: { screen: reviewAnimalScreen },
ListMarks: { screen: listMarksScreen },
CreateMark: { screen: createMarkScreen },
}, {
initialRouteName: 'CreateAnimal',
});
const defaultGetStateForAction = CreateAnimalStack.router.getStateForAction;
CreateAnimalStack.router.getStateForAction = (action, state) => {
if (
state &&
action.type === NavigationActions.BACK &&
state.routeName === 'CreateAnimal' &&
state.routes[state.index].routeName === 'ReviewAnimal' &&
state.index === 1
) {
Alert.alert(
'Alert Title',
'My Alert Msg',
[
{ text: 'Ask me later', onPress: () => console.log('Ask me later pressed') },
{
text: 'Cancel',
onPress: () => {
return null;
},
style: 'cancel',
},
{
text: 'OK', onPress: () => {
const routes = [
{ routeName: 'CreateAnimal' },
];
return {
...state,
routes,
index: 0,
};
}
},
],
{ cancelable: false },
);
return state;
}
return defaultGetStateForAction(action, state);
};
export default CreateAnimalStack;