没有导航道具的反应导航,'dispatch undefined'
React navigation without navigation prop, 'dispatch undefined'
在我的应用程序中,我使用没有导航道具的 React-Navigation 设置导航:https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
但是,当我尝试调用 NavigationService.navigate('LoginScreen');
从 componentDidMount()
我得到 'dispatch undefined'.
当我从 render()
中的 onTap
调用相同的函数时,我按预期导航。
代码:
class SplashScreen extends Component {
componentDidMount() {
NavigationService.navigate('LoginScreen'); // does not work
}
//works at "onPress"
render() {
return (
<View style={styles.container}>
<Text onPress={() => NavigationService.navigate('LoginScreen')}>SplashScreen</Text>
</View>
);
}
}
关于如何解决这个问题有什么想法吗?
您可以使用 withNavigation
。像这样:
import {withNavigation} from 'react-navigation'
class SplashScreen extends Component {
componentDidMount = () => {
this.props.navigation.navigate('LoginScreen'); // Change it
}
render() {
return (
<View style={styles.container}>
<Text onPress={() => this.props.navigation.navigate('LoginScreen')}>SplashScreen</Text>
</View>
)
}
}
export default withNavigation(SplashScreen) // export component like this
withNavigation is a HOC 由 react-navigation
库提供,包装您的组件以传递所需的 navigation
属性。
在我的应用程序中,我使用没有导航道具的 React-Navigation 设置导航:https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
但是,当我尝试调用 NavigationService.navigate('LoginScreen');
从 componentDidMount()
我得到 'dispatch undefined'.
当我从 render()
中的 onTap
调用相同的函数时,我按预期导航。
代码:
class SplashScreen extends Component {
componentDidMount() {
NavigationService.navigate('LoginScreen'); // does not work
}
//works at "onPress"
render() {
return (
<View style={styles.container}>
<Text onPress={() => NavigationService.navigate('LoginScreen')}>SplashScreen</Text>
</View>
);
}
}
关于如何解决这个问题有什么想法吗?
您可以使用 withNavigation
。像这样:
import {withNavigation} from 'react-navigation'
class SplashScreen extends Component {
componentDidMount = () => {
this.props.navigation.navigate('LoginScreen'); // Change it
}
render() {
return (
<View style={styles.container}>
<Text onPress={() => this.props.navigation.navigate('LoginScreen')}>SplashScreen</Text>
</View>
)
}
}
export default withNavigation(SplashScreen) // export component like this
withNavigation is a HOC 由 react-navigation
库提供,包装您的组件以传递所需的 navigation
属性。