如何使用 React Navigation 导航到渲染函数之外的新屏幕,而不使用 JSX?
How do I use React Navigation to navigate to a new screen outside of the render function, and not using 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>
我对 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>