RN:滑回不同的屏幕

RN: Swipe Back to different Screen

我正在尝试让返回滑动转到不同的屏幕

我有以下屏幕顺序 MenuScreenCartScreen 然后是 PaymentScreen

例如,如果 PaymentScreen 中的用户向后滑动,用户应该返回 CartScreen,但我想将用户导航到 MenuScreen 而不是 CartScreen

useEffect(() => {
    navigation.addListener('beforeRemove', e => {

      e.preventDefault();

      navigation.navigate('MenuScreen');
    });
  }, [navigation]);

但我遇到了这个错误:

ERROR  RangeError: Maximum call stack size exceeded.

知道如何解决这个问题吗?或者解决方案?

使用navigation.resetnavigation.popToTop()

useEffect(() => navigation.addListener('beforeRemove', e => {

      e.preventDefault();

      navigation.popToTop();
    });
  , [navigation]);

有两种方法可以实现这一点。以下是指点:

  • StackActions Reference [PREFERRED]:现在您可以从 link 本身了解更多相关信息,但准确地说,如果导航是并不像看起来那么复杂。所以任务是,first moving from Menu -> Cart -> Payment 然后回去的时候 Payment -> Menu。为此,您只需使用 StackAction 使用 navigation:
import { StackActions } from '@react-navigation/native';

// While going from Menu -> Cart
navigation.navigate('Cart');

// While going from Cart -> Payment (Here is the key)
navigation.dispatch(
  StackActions.replace('Payment')
);

现在,当您向后滑动时,您只会看到菜单页面

我们做了什么: 我们从导航堆栈中替换了 Cart,因此堆栈中只有可用的页面,菜单和付款。导致返回菜单。不要忘记使用 navigation.navigate() to go to Cart`。它会帮助你。

  • CommonActions Reference [不太推荐]: 现在这将完全按照您的意愿重置导航,并帮助您实现您想要实现的目标。在这里,您实际上不必担心从 Menu -> Cart 导航时使用什么,但我们确实需要担心从 Cart -> Payment.
  • 导航

缺点:使用此功能时,您将失去在 Menu 页面中取得的所有进度,而您希望在从 Payment -> Menu 使用 SwipeAndroid Hard Back button。此外,它将重置整个导航堆栈,因此您正在用自己的方式创建一个新堆栈。因此,不太喜欢

import { CommonActions } from '@react-navigation/native';

// from Menu -> Cart
navigation.navigate('Cart');

// From Cart -> Payment (Most important) -> Resetting the whole stack
navigation.dispatch(
  CommonActions.reset({
    index: 1,
    routes: [
      { name: 'Menu' },
      { name: 'Payment' },
    ]
  })
);