javascript - 当我尝试设置不同的状态时, this.setState 不是一个函数

标签 javascript reactjs

我想更改 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/

相关文章:

javascript - 无法在 Next 中传递 props

javascript - 将 MQTT 客户端添加到我的 Angular 2 应用程序

javascript - 为什么我会收到一封空电子邮件?

javascript - 错误 : Invalid configuration of route '' . 必须提供以下之一 : component, redirectTo, children or loadChildren at validateNode

javascript - 在自定义 React HOC 中获取 ownProps

Javascript - 替换字符串子字符串内的字符

javascript - 找不到模块,您是说 "*js"吗?

javascript - 在原生 Android View 中渲染 React-Native 组件(UI 组件)

javascript - 如何使用 ES6 编写 ReactJS 高阶组件?

reactjs - React Native 应用程序中的 Redux 非常慢,有大量数据