【问题标题】:State retrieved from react-draft-wysiwyg is always one step behind从 react-draft-wysiwyg 检索到的状态总是落后一步
【发布时间】:2021-11-26 05:06:26
【问题描述】:

我正在尝试实现类似于 Mobile Preview 部分的功能,用户在编辑器中完成操作后,他们所做的更改将显示在 Preview 部分同时进行。

我现在面临的问题是我在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()));
};

【问题讨论】:

    标签: reactjs react-draft-wysiwyg


    【解决方案1】:

    问题在这里:

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

    您有 2 个简单的选项来解决此问题

    • 一是这里根本不用钩子,你可以直接消费你的“状态”
    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
    

    【讨论】:

    • 很详细的解释和解答,谢谢!
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2021-07-12
      • 2021-06-04
      • 1970-01-01
      • 2021-04-09
      • 2021-12-30
      • 2020-07-08
      相关资源
      最近更新 更多