react-draft-wysiwyg获取编辑器状态滞后一步,如何实现预览区同步?
问题根源
React 中的状态更新(setEditorState)是异步批量执行的,你在调用setEditorState(state)后立刻读取editorState变量,拿到的还是更新前的旧状态,所以传给父组件的内容永远滞后一步。
解决方案
你不需要从本地的editorState状态中取数据,直接用handleEditorChange回调传入的最新state参数即可,修改RichTextEditor.js中的handleEditorChange逻辑:
const handleEditorChange = (state) => { setEditorState(state); // 直接用回调拿到的最新state,而非本地还未更新的editorState getContent(convertToRaw(state.getCurrentContent())); };
备选方案
如果你后续有其他逻辑依赖更新后的editorState,也可以通过useEffect监听状态变化后再同步内容:
const handleEditorChange = (state) => { setEditorState(state); }; useEffect(() => { getContent(convertToRaw(editorState.getCurrentContent())); }, [editorState, getContent]);
两种方案都可以实现编辑器内容和预览区的即时同步。
内容的提问来源于stack exchange,提问作者Lance
相关产品推荐
相关产品推荐

