React native splash screen and navigate to different screen

827 views Asked by At

I am beginner in using React Native. I want to display the splash screen for my apps (for 1 second) and the navigate to different screen. I have followed and combined some tutorial but I got an error.

My code is like this:

class SplashScreen extends React.Component {
    static navigationOptions = {header: null,}
    constructor(props){
        super(props);
        this.state = {
            timePassed: false
        };
    }

    render() {
        let that = this;
        setTimeout(function(){that.setState({timePassed: true})}, 1000);
        const { navigate } = this.props.navigation; 

        if (!this.state.timePassed){
           return (
          <View style={styles.splashContainer}>
              <Image source={require('./image/splash_screen.png')} style=
              {styles.splash} />
          </View>
        );
    }
    else{
        () => navigate('Login'); 
    }

}

I got an error to navigate to new screen. Can anyone help me? or is there any better solution? Thank you.

1

There are 1 answers

2
Vorathep Sumetphong On

Try this

class SplashScene extends Component {
  function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  async function sleep(fn, ...args) {
    await timeout(3000);
    return fn(...args);
  }

  resetAndNavigate() {
    const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: 'Login'})
      ]
    })
    this.props.navigation.dispatch(resetAction)
  }
  componentDidMount() {
    sleep.then(
      this.resetAndNavigate()
    )
  }
}