我正在尝试为内置于 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
发布评论