Phi*_*hil 63 javascript settimeout ios react-native
我正在尝试为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',
}}/>
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
加载页面工作一秒钟,然后我想当setTimeout尝试将状态更改为true时,我的程序崩溃:'undefined不是对象(评估this.setState)'.我已经花了几个小时,有关如何修复的想法?
use*_*780 128
经典的javascript错误.
setTimeout(function(){this.setState({timePassed: true})}, 1000)
Run Code Online (Sandbox Code Playgroud)
当setTimeout
运行this.setState
,this
不再CowtanApp
,但window
.如果使用=>
表示法定义函数,es6将自动绑定this
.
setTimeout(() => {this.setState({timePassed: true})}, 1000)
Run Code Online (Sandbox Code Playgroud)
或者,您可以let that = this;
在您的顶部使用a render
,然后切换引用以使用局部变量.
render() {
let that = this;
setTimeout(function(){that.setState({timePassed: true})}, 1000);
Run Code Online (Sandbox Code Playgroud)
Phy*_*hyo 14
为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',
}}/>
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ner 10
如果有人想要它,您还可以使计时器异步并等待它:
export const delay = (ms) => new Promise((res) => setTimeout(res, ms));
Run Code Online (Sandbox Code Playgroud)
用法:
// do something
await delay(500); // wait 0.5 seconds
// do something else
Run Code Online (Sandbox Code Playgroud)
小智 7
const getData = () => {
// some functionality
}
const that = this;
setTimeout(() => {
// write your functions
that.getData()
},6000);
Run Code Online (Sandbox Code Playgroud)
简单的 Settimout 函数在 6000 毫秒后被触发
小智 6
更改此代码:
setTimeout(function(){this.setState({timePassed: true})}, 1000);
Run Code Online (Sandbox Code Playgroud)
到以下内容:
setTimeout(()=>{this.setState({timePassed: true})}, 1000);
Run Code Online (Sandbox Code Playgroud)
在ReactNative .53上,以下对我有用:
this.timeoutCheck = setTimeout(() => {
this.setTimePassed();
}, 400);
Run Code Online (Sandbox Code Playgroud)
setTimeout是ReactNative库函数。
“ this.timeoutCheck”是我的变量,用于保存超时对象。
“ this.setTimePassed”是我在超时时调用的函数。
小智 5
您可以this
通过.bind(this)
直接添加到函数定义的末尾来绑定到您的函数。您将代码块重写为:
setTimeout(function () {
this.setState({ timePassed: true });
}.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97225 次 |
最近记录: |