1

我正尝试在React Native中创建一个加载屏幕,一旦setTimeout函数的时间已满足,它将导航到确认屏幕。目前,屏幕加载,但不会在setTimeout时间间隔后导航到确认屏幕。使用setTimeout导航到另一个组件不会运行

import React from 'react'; 
import { Text, View, Image } from 'react-native'; 
import { Actions as NavigationActions } from 'react-native-router- 
flux'; 

import styles from './styles'; 

export default class ProcessingLoader extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {}; 
} 



componentDidMount() { 
    setTimeout(this.navigateToConfirmation, 3000); 
    } 



navigateToConfirmation() { 
    NavigationActions.checkoutConfirmation({ product: this.props.product, type: 'reset' }); 
    } 



renderLoader() { 
    return (
     <View style={styles.textContainer}> 
     <Text style={styles.loaderText}>Processing Order ...</Text> 
     </View> 
    ); 
    } 



render() { 

    return (
     <View style={{ flex: 1 }}> 
     {this.renderLoader()} 
     </View> 
    ); 
    } 
} 

我在componentDidMount使用的setTimeout以及在渲染尝试。我也试过使用和箭头功能vs不使用箭头功能。我在这里完全错误地使用setTimeout吗?恐怕我不明白为什么3秒后它不会导航到下一个屏幕。提前致谢!

+1

要时刻注意用'this'关键字在JavaScript ...上下文是[怪异](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work),请参阅[这个问题](https://developer.mozilla .org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#The_this_problem)在'setTimeout()'MDN(请注意下面的部分涵盖@Chris的答案) –

+0

谢谢@PatrickBarr! –

回答

0

您不是调用该函数,而是使用括号来做到这一点。 此外,第一个参数是一个回调,所以把你invokation在函数内部,就像这样:

componentDidMount() { 
    setTimeout(function(t){t.navigateToConfirmation()}, 3000, this); 
} 

或箭头功能:

componentDidMount() { 
    setTimeout(() => {this.navigateToConfirmation()}, 3000); 
} 
+1

谢谢@Chris! –

相关问题