【问题标题】:React-Navigation with redux - Back button in StackNavigator nested within TabNavigator triggers back action in both navigatorsReact-Navigation with redux - StackNavigator 中嵌套在 TabNavigator 中的后退按钮触发两个导航器中的后退操作
【发布时间】:2023-03-07 08:32:01
【问题描述】:

我有 redux 的反应导航设置。我的应用程序由一个带有登录和内容屏幕的父 TabBarNavigator 组成。内容屏幕本身就是一个堆栈导航器,其中包含应用程序的主导航。 redux 和导航器的所有其他方面都按预期工作,但 StackNavigator 上的默认后退按钮也会触发它的父 TabBarNavigator 返回。

这是预期的行为吗?我注意到,如果我像这样在 navigationOptions 中定义 headerLeft,它会按预期工作:

static navigationOptions = ({ navigation }) => {
    return {
      headerLeft: (
        <Button transparent onPress={() => { navigation.goBack(); }}><Text>Back</Text></Button>
      )
    };
  };

有人解释一下是什么原因造成的吗?有没有办法让默认的 stackNavigator 后退按钮与 redux 一起使用?

【问题讨论】:

  • 您是否在不定义 headerLeft 的情况下解决了这个问题?
  • 据我了解,如果未指定 headerLeft,则类型为“导航/返回”的调度操作缺少键。我猜它缺少相应的导航对象。
  • 我使用props.navigation.goBack(null) 解决了这个问题。这有点手忙脚乱,但这就是让我知道的原因:reactnavigation.org/docs/navigators/navigation-prop
  • 同样的情况! props.navigation.goBack(null) 不适合我。我想找到一个干净的解决方案在减速器中使用。

标签: react-native redux react-navigation


【解决方案1】:

也许调度一个动作会更好:

    onPress={() => {
      navigation.dispatch(NavigationActions.navigate({
        routeName: '<screen name here>'
      }));
    }}

【讨论】:

    【解决方案2】:

    您可以在 onPress 事件上做一件事,在调用 goBack() 之前,您必须为特定的 redux 调度您的操作:

    static navigationOptions = ({ navigation }) => {
    return {
      headerLeft: (
        <Button 
            transparent 
            onPress={() => { 
              <ACTION_DISPATCH>
              navigation.goBack(); 
            }}>
            <Text>Back</Text>
       </Button>
      )
    };};
    

    【讨论】:

      【解决方案3】:

      在我的情况下,问题稍微复杂一些,因为我使用 react Navigation Redux Integration。

      我的后退动作是一个“后退”动作的调度,但是在我的减速器中,我错过了getStateForAction 方法(状态)的第二个参数

      getStateForAction(动作,状态)

      https://reactnavigation.org/docs/routers/api#getStateForAction-action-state

      所以,在我的导航 redux 中,它与这个反向减速器一起工作:

      export const back = (state) => AppNavigator.router.getStateForAction(NavigationActions.back(), state)
      

      使用此返回操作,来自嵌套导航器的返回不会重置主导航器。

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 2021-12-15
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 2019-11-18
        • 1970-01-01
        • 2010-11-15
        相关资源
        最近更新 更多