我想每5秒更改一次currentIndex
的值,但是当涉及到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);
}
答案 0 :(得分:1)
使用箭头功能:
changeIndex = () =>{
const { currentIndex } = this.state
setInterval( ()=> {
if (currentIndex < 2) {
this.setState({ currentIndex: currentIndex + 1 })
} else {
this.setState({ currentIndex: 0 })
}
}, 5000);
}
答案 1 :(得分:1)
使用箭头功能:
setInterval(() => {
if (currentIndex < 2) {
this.setState({ currentIndex: currentIndex + 1 })
} else {
this.setState({ currentIndex: 0 })
}
}, 5000);