5秒后反应原生更改页面

时间:2017-01-09 13:02:16

标签: react-native

我是反应原生的新手,我不知道如何在5秒后更换页面。

我创建一个 android.index.js 文件,该文件将导航到 LandingPage.js 。我想要做的是,当加载LandingPage时,它将等待5秒钟,然后重定向/导航到另一个页面。

index.android.js

export default class DefaultProject extends Component {
 render() {
    return (
      <Navigator
        renderScene={(route, navigator) =>
          <LandingPage/>
        }
      />
  )

LandingPage.js

export default class LandingPage extends Component {
  render() {
    return (
        <Image source={require('./images/event3.jpeg')} 
        style={styles.container} />
        //How to redirect to another page from here after 5 secs?

    );
  }
}

2 个答案:

答案 0 :(得分:11)

您可以使用简单的setTimeout,就像在标准JS设置中一样:

export default class LandingPage extends Component {
    componentDidMount(){
         // Start counting when the page is loaded
         this.timeoutHandle = setTimeout(()=>{
              // Add your logic for the transition
         }, 5000);
    }

    componentWillUnmount(){
         clearTimeout(this.timeoutHandle); // This is just necessary in the case that the screen is closed before the timeout fires, otherwise it would cause a memory leak that would trigger the transition regardless, breaking the user experience.
    }

    render() {

    return (
        <Image source={require('./images/event3.jpeg')} 
        style={styles.container} />
        //How to redirect to another page from here after 5 secs?

    );
  }


}

答案 1 :(得分:1)

我正在使用lodash:

export default class Splash extends React.Component {

    constructor(props) {
        super(props);
    }

    async componentWillMount() {
        _.delay(() => this.props.navigator.replace({ component: 'login' }), 1000);
    }

    render() {
        return (
            ...
        );
    }
}

这仅适用于Navigator设置的情况。查看这篇文章:

React Native Navigator — Navigating Like A Pro in React Native