比setState更快的方法来更新React中的数据

时间:2020-05-26 12:13:54

标签: javascript reactjs react-chartjs

我正在使用react-chartjs-2显示不断更新的趋势线。为了设置趋势线的值,我使用了react的setState函数,但我意识到,每次更改状态大约需要40毫秒。因此,我想知道是否有一种方法可以更快地更改状态,或者在不使用组件状态的情况下将数据传递到图表对象。

我的代码来更新状态:

class CurveSection extends React.Component {

    state = {
        data: { ... },
        options: { ... },
        startTime: 0,
        lastUpdateTime: 0
    }


    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.updateGraphs = this.updateGraphs.bind(this);
    }

    // updates graph data for CurveGraphs
    // called every 10 ms, but executed less frequently due to this.setState duration
    // therefore has to calculate each time how many values have to be updated in order to 
    // create a timematching graph
    updateGraphs() {
        var actualTime = new Date();
        var elementsToUpdate = Math.round((actualTime.getTime() - this.state.lastUpdateTime)/(1000/samplingFrequency) % numberOfValues)
        var queuePos = Math.round((actualTime.getTime() - this.state.startTime)/(1000/samplingFrequency) % numberOfValues)

        var dataCopy = this.state.data

        // doing stuff to data        

        this.setState({lastUpdateTime: actualTime.getTime(), data: dataCopy});
    }

    render () {
        return (
            <div className="CurveSection">
                <CurveGraph data={this.state.data.data1} options={this.state.options} />
                <CurveGraph data={this.state.data.data2} options={this.state.options} />
                <CurveGraph data={this.state.data.data3} options={this.state.options} />
                <CurveGraph data={this.state.data.data4} options={this.state.options} />
            </div>
        )
    };
}

0 个答案:

没有答案