这是我的代码
componentDidMount() {
let that = this;
setInterval(() => {
that.setState({number: 1});
}, 2000);
}
我写了'let that = this;'
,但这也是错误。在 2 秒内它执行了不止一次。
最佳答案
为什么不在 setInterval
中使用 this
本身?您已使用fat arrow函数,所以你仍然可以在里面使用 this
。
这是一个示例代码:
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>
);
}
关于javascript - setInterval()中 react 原生setState,然后setInterval执行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42922854/