繁体   English   中英

只有在父组件完成重新渲染后才调用子组件中的方法

[英]Call a method in child component only after parent completes re-render

我有一个由父组件<HeatMap />显示的图形质量较低的图形。 HeatMap有一个子组件<MyButton {...data}> MyButton基本上是一个按钮,用于下载图形图像。 我的要求是:单击按钮后,应将父级( HeatMap )重新渲染为高质量的 svg 图像。 只有在那之后,下载才会发生。

我能够实现的目标:第一次单击按钮时,图像质量变为 svg,但下载了png图像。 我认为下载在父级完全呈现之前开始。

代码:

class HeatMap extends Component {
  constructor (props) {
    super(props);
    this.state = {
      getSVG: false,
      loadedData: [],
    }
  }
  render () {
   const { getSVG, loadedData } = this.state;
   return (
    <Fragment>
      {getSVG
        ? <HeatmapSeries colorType="literal" data={loadedData} /> // svg graph
        : <HeatmapSeriesCanvas colorType="literal" data={loadedData} />} // png(low-qlty)
      <MyButton 
        {...this.props}
        svgFunction={(required) => this.setState({ getSVG: true})}
        getSVG={getSVG} 
       />
    </Fragment>
  )
  }
}
class MyButton extends Component {
  render() {
    return (
      <Button size="small" icon="download" onClick={this._downloadSVG} >SVG</Button>
    )
  }
  /**
   * Generate the image and the download action
   * @return {void}
  **/
  async _downloadSVG() {
    const { svgFunction } = this.props;
    if (typeof svgFunction === 'function') {
      svgFunction(); // re-render the graph as a vector (try to re-render parent first)
    }
    methodToDownloadGraph({...this.props}); // graph svg is passed as argument
  }
}

问题是: methodToDownloadGraph之前完成,父级的重新渲染完成。 这是我想要实现的图片: 在此处输入图像描述

试试这个

async _downloadSVG() {
        const { svgFunction } = this.props;
        if (typeof svgFunction === 'function') {
          await svgFunction(); // Add this line as it is
        }
        methodToDownloadGraph({...this.props}); // graph svg is passed as argument
      }

React 的setState是一个异步的 function,这意味着它不会在调用它后立即更新 state。 如果您想在 state 更新后进行一些操作,那么您需要将回调作为第二个参数传递给setState function。

要解决此问题,您需要在HeatMap组件而不是Button组件中调用methodToDownloadGraph function。

你可以这样做:

svgFunction={(required) => this.setState({ getSVG: true}, () => methodToDownloadGraph())}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM