首页 > 解决方案 > 我无法更新我的图表(在 react-chartjs-2 中)

问题描述

我想每秒钟更新一次图表

这是我的代码:

class Chart extends Component {

    constructor(props) {
        super(props);
        this.state = {
            chartData: {
                // my charData
            }
        }

        setInterval(function(){
           this.props.changeHandler();
        }, 500); 
    }


    changeHandler() {
        this.state.update();
    } 

    // my render
}

但我有这个错误:this.props is undefined (On the setInterval)

任何人都可以帮助我吗?

标签: chart.js

解决方案


函数有自己的 this 上下文,因此您必须在 setInterval 之前将 this 上下文存储在局部变量中,或者使用箭头函数而不是函数

setInterval(() => {
       this.props.changeHandler();
    }, 500); 

推荐阅读