Reputation: 671
In my app I set up my navigation with React-Navigation without navigation props like this: https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
However, when I try to call NavigationService.navigate('LoginScreen');
from componentDidMount()
I get 'dispatch undefined'.
When I call the same function from the onTap
inside render()
, I navigate as expected.
Code:
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>
);
}
}
Any ideas on how to solve this?
Upvotes: 0
Views: 256
Reputation: 1155
You can use withNavigation
. Like this:
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 supplied by the react-navigation
library that wraps your component to pass the required navigation
prop.
Upvotes: 3