如何使用 React 导航导航到渲染函数之外的新屏幕,而不是使用 JSX



我在React,React Native和React Navigation方面相当陌生。取得了一些进展,但遇到了这个问题。

通常我会通过执行以下操作导航到新页面:

<Button
  text='View Details' onPress={() => 
  this.props.navigation.navigate('AccountScreen')} />

但是,我目前正在尝试导航到.fetch()中的新屏幕,并想知道我需要做什么不同的事情。

请参阅下面的代码:

// AppNavigation.js:
...
const PrimaryNav = StackNavigator({
  HomeScreen: { screen: HomeScreen },
  AccountScreen: { screen: AccountScreen }
});

// HomeScreen.js
...
handlePress = (navigator) => {
  fetch('https://example.com/this/url/works' + this.state.accountName, lookUpObject ).then( function(response) {
    if(response.ok) {
      // this does not work. 
      // returns this error:
      // "undefined is not an object (evaluating 'navigator.navigate')"
      navigator.navigate( 'AccountScreen', { "accountName": this.state.accountName } );
    }
  })
}
render () {
  const { navigate } = this.props.navigation;
  reutrn (
    <ButtonCTA onPress={this.handlePress}>Go to account page</ButtonCTA>
  )
}

现在我收到以下错误: "undefined is not an object (evaluating 'navigator.navigate')"

您只是忘记将导航器传递到handlePress您的按钮代码应如下所示:

<ButtonCTA onPress={ ()=>this.handlePress(this.props.navigation) }>Go to account page</ButtonCTA>

最新更新