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! –

相關問題