简体   繁体   中英

Slate: How to find when Editor has fully rendered

I would like to have a page that renders a Slate Editor, retrieves a document from an API, and then prints the window when the Editor has updated and finished re-rendering. How can I identify when the Editor has re-rendered?

Example code:

  componentDidMount() {
    $.get('/api/')
      .done((data) => {
        this.setState({ document: Value.fromJSON(data) });
        // workaround to try and make sure document is rendered
        // what can I do here instead??
        setTimeout(() => window.print(), 500);
      });
  }

  render() {
    const { document } = this.state;

    return (
        <Editor
          value={document}
          readOnly
          ...
        />
    );

I tried using componentDidUpdate in the parent component:

componentDidUpdate(prevProps, prevState) {
    window.print();
}

But the function gets triggered before the editor is fully rendered, so the text doesn't display in the Print dialog:

componentDidUpdate太早了

Use the componentDidUpdate life-cycle method in the class that renders your Editor component.

componentDidUpdate() {
    if(this.state.document !== prevState.document) }
        // Here you know that the Editor component has re-rendered
    }
}

As noted in the documentation I linked, the componentDidUpdate method does not get triggered on initial render. This won't be an issue for your use case though because you are awaiting asynchronously loaded data.

You can use componentDidUpdate to track when state gets updated. When you update this.state.document , it looks like that will trigger a re-render of the Editor component since it is being passed down as a prop. Unless Editor provides a callback for when it renders, you will have to do the setTimeout hack:

componentDidUpdate(prevProps, prevState) {
    if(this.state.document !== prevState.document) {
        setTimeout(() => window.print(), 500);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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