2

我想要一个呈现Slate编辑器的页面,从 API 检索文档,然后在编辑器更新并完成重新呈现时打印窗口。如何识别编辑器何时重新渲染?

示例代码:

  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
          ...
        />
    );

我尝试componentDidUpdate在父组件中使用:

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

但是该函数在编辑器完全呈现之前被触发,因此文本不会显示在“打印”对话框中:

componentDidUpdate 过早

4

2 回答 2

2

componentDidUpdate在呈现Editor组件的类中使用生命周期方法。

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

如我链接的文档中所述,该componentDidUpdate方法不会在初始渲染时触发。不过,这对您的用例来说不是问题,因为您正在等待异步加载的数据。

于 2018-03-01T16:36:39.553 回答
1

您可以componentDidUpdate用来跟踪状态何时更新。当您更新this.state.document时,看起来这将触发Editor组件的重新渲染,因为它被作为道具传递下来。除非Editor在渲染时提供回调,否则您将不得不执行以下操作setTimeout

componentDidUpdate(prevProps, prevState) {
    if(this.state.document !== prevState.document) {
        setTimeout(() => window.print(), 500);
    }
}
于 2018-03-01T16:04:54.620 回答