如何知道Draft.js插件何时准备就绪?

时间:2017-11-15 00:51:17

标签: javascript reactjs draftjs

我正在使用Draft.js插件Linkify

我正在尝试从本地存储加载内容,然后将其链接。

现在我必须使用setTimeout等待linkifyPlugin准备就绪。如果没有,加载的内容将是纯文本,而不是链接。

有没有像我可以用来知道插件何时准备好的事件?

class MyComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  componentDidMount() {
    // ...
    if (hasDraft) this.loadEditor(draftFromLocalStorage);
  }


  loadEditor = rawContent => {
    // here I have to use setTimeout to wait linkifyPlugin ready
    setTimeout(() => {
      const editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
      this.setState({ editorState });
    }, 5);
  };


  render() {
    return (
      <Editor
        editorState={editorState}
        plugins={[linkifyPlugin]}
        onChange={this.onEditorChange} />
    );
  }
}

2 个答案:

答案 0 :(得分:0)

尝试使用Promise

loadEditor(rawContent){
  return new Promise((resolve, reject) => {
    let editorState = EditorState.push(this.state.editorState, convertFromRaw(rawContent));
    resolve(editorState);
  });
}
//call it after component has mounted
componentDidMount(){
  this.loadEditor(draftFromLocalStorage).then(data => this.setState({ editorState: data }));
}

答案 1 :(得分:0)

奇怪,看一下源代码,没有理由认为该插件有异步代码:https://github.com/draft-js-plugins/draft-js-plugins/tree/master/draft-js-linkify-plugin

您可以尝试在此功能上设置断点:https://github.com/draft-js-plugins/draft-js-plugins/blob/master/draft-js-linkify-plugin/src/linkStrategy.js

为状态中的每个块调用该函数,因此您应该能够看到文本是否由Linkify处理。如果你删除超时并且仍在调用函数,那么问题应该在其他地方(因为这意味着你有渲染问题,而不是实际处理)。