Javascript React Native 中的 setTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34504322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setTimeout in React Native
提问by Phil
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:
我正在尝试为内置于 React Native 的 iOS 应用加载启动画面。我正在尝试通过类状态然后 setTimeout 函数来完成此操作,如下所示:
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',
}}/>
);
}
}
}
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?
加载页面工作了一秒钟,然后我猜当 setTimeout 尝试将状态更改为 true 时,我的程序崩溃了:'undefined is not an object (evaluating this.setState)'。我已经研究了几个小时,关于如何解决它的任何想法?
回答by oliversisson
Classic javascript mistake.
经典的 javascript 错误。
setTimeout(function(){this.setState({timePassed: true})}, 1000)
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
,this
不再CowtanApp
,但window
。如果您使用=>
符号定义函数,es6 将自动绑定this
。
setTimeout(() => {this.setState({timePassed: true})}, 1000)
Alternatively, you could use a let that = this;
at the top of your render
, then switch your references to use the local variable.
或者,您可以let that = this;
在 顶部使用 a render
,然后切换您的引用以使用局部变量。
render() {
let that = this;
setTimeout(function(){that.setState({timePassed: true})}, 1000);
If not working, use bind
.
如果不起作用,请使用bind
.
setTimeout(
function() {
this.setState({timePassed: true});
}
.bind(this),
1000
);
回答by Phyo
Write a new function for settimeout. Pls try this.
为 settimeout 编写一个新函数。请试试这个。
class CowtanApp extends Component {
constructor(props){
super(props);
this.state = {
timePassed: false
};
}
componentDidMount() {
this.setTimeout( () => {
this.setTimePassed();
},1000);
}
setTimePassed() {
this.setState({timePassed: true});
}
render() {
if (!this.state.timePassed){
return <LoadingPage/>;
}else{
return (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
);
}
}
}
回答by wandhi Zakari
Change this code:
更改此代码:
setTimeout(function(){this.setState({timePassed: true})}, 1000);
to the following:
到以下几点:
setTimeout(()=>{this.setState({timePassed: true})}, 1000);
回答by david m lee
On ReactNative .53, the following works for me:
在 ReactNative .53 上,以下对我有用:
this.timeoutCheck = setTimeout(() => {
this.setTimePassed();
}, 400);
'setTimeout' is the ReactNative library function.
'this.timeoutCheck' is my variable to hold the time out object.
'this.setTimePassed' is my function to invoke at the time out.
'setTimeout' 是 ReactNative 库函数。
'this.timeoutCheck' 是我用来保存超时对象的变量。
'this.setTimePassed' 是我在超时时调用的函数。
回答by Scott Carpenter
You can bind this
to your function by adding .bind(this)
directly to the end of your function definition. You would rewrite your code block as:
您可以this
通过.bind(this)
直接添加到函数定义的末尾来绑定到您的函数。您将代码块重写为:
setTimeout(function () {
this.setState({ timePassed: true });
}.bind(this), 1000);
回答by krishnazden
const getData = () => {
// some functionality
}
const that = this;
setTimeout(() => {
// write your functions
that.getData()
},6000);
Simple, Settimout function get triggered after 6000 milliseonds
简单的 Settimout 函数在 6000 毫秒后被触发
回答by Alex Buicescu
There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. Thisgithub issue helped me find the problem.
当电话/模拟器的时间与服务器之一(运行 react-native 打包程序的时间)不同时,似乎存在问题。就我而言,手机和电脑的时间相差 1 分钟。同步它们后(没有做任何花哨的事情,手机设置为手动时间,我只是将其设置为使用网络(sim)提供的时间),一切正常。这个github问题帮助我找到了问题。
回答by UtkarshPramodGupta
Never call
setState
insiderender
method
从不调用
setState
内部render
方法
You should never evercall setState
inside the render
method. Why?calling setState
eventually fires the render
method again. That means you are calling setState (mentioned in your render
block) in a loop that would never end. The correct way to do that is by using componentDidMount
hook in React, like so:
你永远不应该setState
在render
方法内部调用。为什么?调用setState
最终会render
再次触发该方法。这意味着您render
在一个永远不会结束的循环中调用 setState(在您的块中提到)。正确的方法是componentDidMount
在 React 中使用钩子,如下所示:
class CowtanApp extends Component {
state = {
timePassed: false
}
componentDidMount () {
setTimeout(() => this.setState({timePassed: true}), 1000)
}
render () {
return this.state.timePassed ? (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
) : <LoadingPage/>
}
}
PS Use ternary operators for cleaner, shorter and readable code.
PS 使用三元运算符来获得更清晰、更短且可读的代码。
回答by Dunken_sai
Same as above, might help some people.
和上面一样,可能会帮助一些人。
setTimeout(() => {
if (pushToken!=null && deviceId!=null) {
console.log("pushToken & OS ");
this.setState({ pushToken: pushToken});
this.setState({ deviceId: deviceId });
console.log("pushToken & OS "+pushToken+"\n"+deviceId);
}
}, 1000);
回答by Eric Wiener
In case anyone wants it, you can also make the timer async and await it:
如果有人想要它,您还可以使计时器异步并等待它:
export const delay = (ms) => new Promise((res) => setTimeout(res, ms));
Usage:
用法:
// do something
await delay(500); // wait 0.5 seconds
// do something else