我正在使用Draft.js插件Linkify。
我正在尝试从本地存储加载内容,然后将其链接。
现在我必须使用setTimeout
来等待链接插件准备就绪。否则,加载的内容将是未链接的纯文本。
有什么方法可以像事件一样,我可以用来知道插件何时准备就绪?
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} />
);
}
}
尝试使用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 }));
}
奇怪的是,查看源代码,没有理由认为该插件具有异步代码: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 处理。如果删除超时并且函数仍在调用,则问题应该出在其他地方(因为这意味着渲染有问题,而不是实际处理(。