我想更改 currentIndex
的值每 5 秒一次,但是当涉及 this.setState
时我收到Uncaught TypeError: this.setState is not a function
这是我的代码:
constructor() {
super()
this.state = {
currentIndex: 0,
}
}
componentDidMount() {
this.changeIndex()
}
changeIndex() {
const { currentIndex } = this.state
setInterval(function () {
if (currentIndex < 2) {
this.setState({ currentIndex: currentIndex + 1 })
} else {
this.setState({ currentIndex: 0 })
}
}, 5000);
}
最佳答案
使用箭头功能:
setInterval(() => {
if (currentIndex < 2) {
this.setState({ currentIndex: currentIndex + 1 })
} else {
this.setState({ currentIndex: 0 })
}
}, 5000);
关于javascript - 当我尝试设置不同的状态时, this.setState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086675/