【问题标题】:Navigating to another component using setTimeout does not run使用 setTimeout 导航到另一个组件不会运行
【发布时间】:2017-07-06 20:02:32
【问题描述】:

我正在尝试在 React Native 中创建一个加载屏幕,一旦 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。我也尝试过使用箭头函数与不使用箭头函数。我在这里使用 setTimeout 完全错误吗?恐怕我不明白为什么它不会在 3 秒后导航到下一个屏幕。提前致谢!

【问题讨论】:

  • 应始终小心 javascript 中的 this 关键字...上下文为 weird,请参阅 setTimeout() MDN 中的 the this problem(请注意以下部分涵盖了 @Chris 的答案)
  • 谢谢你,@PatrickBarr!
  • 谢谢你的帖子,我实际上是在寻找为什么我的导航在 componentdidmount() 中不起作用的答案,只是意识到我必须创建一个函数,然后从那里调用导航

标签: javascript reactjs react-native settimeout react-native-router-flux


【解决方案1】:

您没有调用该函数,请使用括号来执行此操作。 另外,第一个参数是一个回调,所以把你的调用放在一个函数中,像这样:

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

或在箭头函数中:

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

【讨论】:

  • 谢谢你,@Chris!
猜你喜欢
  • 2017-02-08
  • 1970-01-01
  • 2020-09-24
  • 2020-09-01
  • 1970-01-01
  • 2018-05-31
  • 2018-05-31
  • 2019-03-03
  • 2016-08-13
相关资源
最近更新 更多