gpt4 book ai didi

reactjs - react 中 setTimeout 中的 this.setState

转载 作者:行者123 更新时间:2023-12-03 14:13:42 29 4
gpt4 key购买 nike

更新状态的函数:

animate() {
setInterval(function(){
setTimeout( this.setState({
a: '123'
}), 1000);
}, 4000);
}

调用的方法:

componentDidMount() {
this.animate();
}

错误:

Uncaught TypeError: this.setState is not a function

然后尝试下一个代码:

animate() {
setInterval(function(){
setTimeout( () => {this.setState({
a: '123'
})}, 1000);
}, 4000);
}

下一个错误是:

Uncaught TypeError: _this2.setState is not a function

最佳答案

问题源于您对 setInterval 的定义。

当你执行setInterval(function() {...})时,this关键字不再绑定(bind)到React组件,而是绑定(bind)到它被调用的函数由于引入了新范围。

您可以将其切换为:

animate() {
const self = this

setInterval(function() {
setTimeout(() => self.setState({ a: '123' }), 1000)
}, 4000)
}

这样,在引入新作用域之前,将 self 分配给 this 的 React 组件值,或者您可以使用所有箭头函数来保留 this 引用组件的关键字:

animate() {
setInterval(() => {
setTimeout(() => this.setState({ a: '123' }), 1000)
}, 4000)
}

关于reactjs - react 中 setTimeout 中的 this.setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464241/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com