你好,我试图在React中模拟批量读取连续数据。目前,模拟数据有10个对象,我正尝试每5秒将2个对象加载到状态中。我使用的间隔是在状态具有所有值时停止的。状态会使用计时器正确更新,但是只有在第一次状态更改后才呈现组件,这使我感到困惑。我感觉这可能是并发问题,但我可能是错的。
export default class Example extends PureComponent {
constructor() {
super();
this.state = {
batchDataState: []
};
}
interval = 0;
batchData = [];
componentDidMount() {
this.batchData.push(data[this.batchData.length]);
this.batchData.push(data[this.batchData.length]);
this.interval = setInterval(() => this.loadBatchedData(), 5000);
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.state.batchDataState !== prevState.batchDataState) {
console.log(this.state.batchDataState)
}
}
stopInterval = () => {
clearInterval(this.interval);
};
loadBatchedData = () => {
if (this.batchData.length < data.length) {
this.batchData.push(data[this.batchData.length]); //i
this.batchData.push(data[this.batchData.length]); //i+1
this.setState({batchDataState: this.batchData}, ()=> console.log); // changes the state but doesn't lead to rendering
} else {
this.stopInterval();
}
};