当我尝试设置其他状态时,this.setState不是函数

时间:2019-09-24 19:01:21

标签: javascript reactjs

我想每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);
    }

2 个答案:

答案 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);