You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:09:03