React Native 中的 setTimeout

编程入门 行业动态 更新时间:2024-10-08 00:28:14
本文介绍了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 is not an object (evaluating 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时,this不再是CowtanApp,而是window.如果使用 => 符号定义函数,es6 将自动绑定 this.

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)

或者,您可以在 render 顶部使用 let that = this;,然后将引用切换为使用局部变量.

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);

如果不起作用,请使用bind.

If not working, use bind.

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

更多推荐

React Native 中的 setTimeout

本文发布于:2023-11-27 21:28:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:React   Native   setTimeout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!