简体   繁体   English

在setInterval()中反应本机setState,然后setInterval执行错误

[英]react native setState in setInterval(), then setInterval executes error

Here is my code 这是我的代码

componentDidMount() {
    let that = this;
    setInterval(() => {
        that.setState({number: 1});
    }, 2000);
}

I have writen 'let that = this;' 我写了'let that = this;' , but it's also error. ,但这也是错误。 In 2 seconds it executes more than once. 在2秒内,它执行一次以上。

Why aren't you using this itself in the setInterval ? 为什么不在setInterval使用this本身呢? You have used the fat arrow function, so you still can use this inside. 您已经使用了粗箭头功能,因此仍可以在内部使用this

Here's a sample code: 这是一个示例代码:

constructor (props) {
    super(props)
    this.state = {
        number: 0
    } 
  }

componentDidMount(){
  setInterval(() => {
      this.setState({number: parseInt(this.state.number, 10) + 1 });
  }, 2000);

}

render() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center',}}>
      <Text>
       {this.state.number }
      </Text>
    </View>
  );
}

Expo Demo 世博演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM