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:
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
Classic javascript mistake.
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({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.
render() {
let that = this;
setTimeout(function(){that.setState({timePassed: true})}, 1000);
If not working, use bind
.
setTimeout(
function() {
this.setState({timePassed: true});
}
.bind(this),
1000
);
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:
setTimeout(function () {
this.setState({ timePassed: true });
}.bind(this), 1000);
const getData = () => {
// some functionality
}
const that = this;
setTimeout(() => {
// write your functions
that.getData()
},6000);
Simple, Settimout function get triggered after 6000 milliseonds
Simple setTimeout(()=>{this.setState({loaded: true})}, 1000);
use this for timeout.
Never call
setState
insiderender
method
You should never ever call 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:
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.