setTimeout in React Native
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);
Write a new function for settimeout. Pls try this.
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', }}/> );}}}
Change this code:
setTimeout(function(){this.setState({timePassed: true})}, 1000);
to the following:
setTimeout(()=>{this.setState({timePassed: true})}, 1000);