对我来说,componentDidUpdate单独或窗口。requestAnimationFrame本身并不能解决问题,但是下面的代码可以工作。
// Worked but not succinct
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.state.refreshFlag) { // in the setState for which you want to do post-rendering stuffs, set this refreshFlag to true at the same time, to enable this block of code.
window.requestAnimationFrame(() => {
this.setState({
refreshFlag: false // Set the refreshFlag back to false so this only runs once.
});
something = this.scatterChart.current.canvas
.toDataURL("image/png"); // Do something that need to be done after rendering is finished. In my case I retrieved the canvas image.
});
}
}
后来我测试requestAnimationFrame注释,它仍然完美地工作:
// The best solution I found
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.state.refreshFlag) { // in the setState for which you want to do post-rendering stuffs, set this refreshFlag to true at the same time, to enable this block of code.
// window.requestAnimationFrame(() => {
this.setState({
refreshFlag: false // Set the refreshFlag back to false so this only runs once.
});
something = this.scatterChart.current.canvas
.toDataURL("image/png"); // Do something that need to be done after rendering is finished. In my case I retrieved the canvas image.
// });
}
}
我不确定这是否只是一个巧合,额外的setState诱导时间延迟,以便在检索图像时,绘图已经完成(我将得到旧的画布图像,如果我删除setState)。
或者更可能的是,这是因为setState需要在所有内容呈现之后执行,所以它强制等待呈现完成。
我倾向于相信后者,因为根据我的经验,在我的代码中连续调用setState会导致每一个都在最后一个渲染完成后才被触发。
最后,我测试了以下代码。如果this.setState ({});不更新组件,但等到渲染完成,这将是最终的最佳解决方案,我认为。然而,它失败了。即使传递一个空的{},setState()仍然更新组件。
// This one failed!
componentDidUpdate(prevProps, prevState, snapshot) {
// if (this.state.refreshFlag) {
// window.requestAnimationFrame(() => {
this.setState({});
something = this.scatterChart.current.canvas
.toDataURL("image/png");
// });
// }
}