【问题标题】:Are my expectations about React navigation correct?我对 React 导航的期望是否正确?
【发布时间】:2018-12-24 11:10:07
【问题描述】:

这可能是我缺乏理解,但如果我对 React 导航的期望是错误的,谁能解释一下?

我的应用或多或少是一个问卷调查,其中一个屏幕可以处理所有问题。基本上,它使用新的问题 ID 导航到自身。这会获取正确的数据并显示它。工作正常,但是当我按下返回时,我没有转到上一个问题,而是转到主页。我使用 expo 和他们的recommended navigation

我的期望是当我从最后一页返回时:

Homepage => QuestionPage(id=1) => QuestionPage(id=3) 

我会返回 id = 1 的 QuestionPage,但它会转到主页。我在两个页面上都使用 withNavigation 来维护导航道具。

这种期望是错误的还是正确的导航行为?如果是这样,任何线索都可以得到我的预期行为。

【问题讨论】:

    标签: reactjs navigation native expo stack-navigator


    【解决方案1】:

    从单页实现反应导航多页应用。您需要在项目中添加“react-router-dom”包。

    import {
      Route as Router,
      Switch,
      Redirect
    } from 'react-router-dom';
    

    您必须为导航页面设置路由器,如下所示。

    <Switch>
    <Router exact path="/questionpage/:handle" component={Questionpage} />
    </Switch>
    

    在问题页面路由器:

    this.props.match.params.handle // will help to get page number
    

    通过使用上述语法,您可以获得页码并能够准确地获取您想要的数据。

    【讨论】:

    • 感谢您的快速回复。我是否正确这是针对 React 而不能在 React-native 中使用的?
    • Victor H 如果你想使用原生 react 那么你需要使用不同的路由包来帮助原生理解动作。即react-navigation。如果信息有帮助,请不要忘记投票。
    • 我使用的(如前所述)我使用 react-native 和 react-navigation 包括 withNavigation
    【解决方案2】:

    原来如此简单。而不是

    this.props.navigation.navigate('Question', {id=40})}
    

    我不得不写

    this.props.navigation.push('Question', {id=40})}
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 StackNavigator 并从后退按钮上的 QuestionPage 中使用

       this.props.navigation.goBack();
      

      而不是

      this.props.navigation.navigate('Screen')} 
      

      它应该工作!

      如果你想在 react 导航屏幕上自定义导航,我建议在后面的 Android 上听 didFocus 像这样:

      _didFocusSubscription;
        _willBlurSubscription;
      
        constructor(props) {
          super(props);
          this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
            BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
          );
        }
      
        componentDidMount() {
          this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
            BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
          );
        }
      hardwareBackPress = () => {  this.props.navigation.navigate('Screen')} }
      

      更准确的示例和相关文档在这里https://reactnavigation.org/docs/en/custom-android-back-button-handling.html

      【讨论】:

      • 我指的是设备上的物理后退按钮(和渲染的),但谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多