React Native中的setTimeout [英] setTimeout in React Native

查看:275
本文介绍了React Native中的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为React Native内置的iOS应用加载启动画面。我试图通过类状态然后使用setTimeout函数完成此操作,如下所示:

I'm trying to load a splash screen for an iOS app built in React Native. I'm trying to accomplish this through class states and then a setTimeout function as follows:

class CowtanApp extends Component {
  constructor(props){
    super(props);
    this.state = {
      timePassed: false
    };
  }

  render() {
    setTimeout(function(){this.setState({timePassed: true})}, 1000);
    if (!this.state.timePassed){
      return <LoadingPage/>;
    }else{
      return (
        <NavigatorIOS
          style = {styles.container}
          initialRoute = {{
            component: LoginPage,
            title: 'Sign In',
          }}/>
      );
    }
  }
}

加载页面适用于第二,然后我猜当setTimeout尝试将状态更改为true时,我的程序崩溃:'undefined不是对象(评估this.setState)'。我已经花了几个小时,有关如何修复它的任何想法?

The loading page works for a second, and then I guess when setTimeout tries to change the state to true, my program crashes: 'undefined is not an object (evaluating this.setState)'. I've been going at this for a couple of hours, any ideas on how to fix it?

推荐答案

经典的javascript错误。

Classic javascript mistake.

setTimeout(function(){this.setState({timePassed: true})}, 1000)

setTimeout 运行 this.setState 不再是 CowtanApp ,但窗口。如果使用 => 表示法定义函数,es6将自动绑定

When setTimeout runs this.setState, this is no longer CowtanApp, but window. If you define the function with the => notation, es6 will auto-bind this.

setTimeout(() => {this.setState({timePassed: true})}, 1000)

或者,你可以使用让你的<=; code>在你的 render ,然后切换你的引用以使用局部变量。

Alternatively, you could use a let that = this; at the top of your render, then switch your references to use the local variable.

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

这篇关于React Native中的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆