从 react-draft-wysiwyg 检索到的状态总是落后一步

State retrieved from react-draft-wysiwyg is always one step behind

我正在尝试实现类似 移动预览 部分的功能,用户在编辑器中完成操作后,他们所做的更改将显示在同时预览节。

我现在面临的问题是我在 Bulletin.js 中使用的从编辑器检索 html 内容的方法似乎落后了 1 步(因为我需要执行某些操作,例如单击任意位置或检索在编辑器中执行的最后一个操作)。

我想做到即时更改而不是落后一步,这样当用户执行更改字体颜色等操作时,它会立即反映到预览部分。

Bulletin.js

const getContent = (htmlContentProp) => {
    setHtmlContent(draftToHtml(htmlContentProp));
};

<RichTextEditor getContent={getContent} htmlContent={htmlContent} />

RichTextEditor.js

const handleEditorChange = (state) => {
    setEditorState(state);
    getContent(convertToRaw(editorState.getCurrentContent()));
};

问题在这里:

const handleEditorChange = (state) => {
    setEditorState(state); // this is asynchronous
    // so this will most likely be old value
    getContent(convertToRaw(editorState.getCurrentContent()));
};

您有 2 个简单的选择来解决这个问题

  • 一个是这里根本不用hook,你可以直接消费你的“state”
const handleEditorChange = (state) => {
    getContent(convertToRaw(state.getCurrentContent()));
};
  • 其他选项是使用 useEffect 如果您出于某种原因需要此处的钩子,这是更“正确”的选项
const handleEditorChange = (state) => {
    setEditorState(state); // this is asynchronous
};

useEffect(() => { 
    getContent(convertToRaw(editorState.getCurrentContent()));
}, [editorState]); // this effect will trigger once the editorState actually changes value

当此行 getContent(convertToRaw(editorState.getCurrentContent()))handleEditorChange 函数中运行时,editorState 尚未更新为最新值。由于 React 状态更新是 async

您可以使用 handleEditorChange 中的 state 参数来获取如下所示的最新数据

const handleEditorChange = (state) => {
  setEditorState(state);
  getContent(convertToRaw(state.getCurrentContent()));
};

或使用 useEffect 根据子状态的变化更新父状态。