setTimeout in React Native

前端 未结 11 2112
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 05:43

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:

11条回答
  •  甜味超标
    2020-12-14 05:52

    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
    );
    

提交回复
热议问题