从后端获取数据,然后使用 draft-js 将数据传递给 editorState

Fetch data from the backend, then pass the data to editorState using draft-js

我正在创建一个组件,它将使用 draft-js 显示来自后端的数据。来自后端的数据也使用 draft-js 存储。数据没有显示,也没有错误信息。

来自后端的示例数据在传递给 viewContent.js

之前正在被解析

你好世界

我尝试创建一个变量来检查代码是否正常工作。我尝试了这种方法 const sample = <p>Hello World。如果在 contenBlocks 上传递这个,这个就可以工作。

viewContent.js

import {
  EditorState,
  ContentState,
  convertFromHTML,
} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';

const viewContent = ({ content }) => {
    const [editorState, setEditorState] = useState();

  const clearState = () => {
    ContentState.createFromText('');
  };

  const handleEditorChange = (state) => {
    setEditorState(state);
    let currentContentAsHTML = JSON.stringify(
      draftToHtml(convertToRaw(editorState.getCurrentContent()))
    );
    convertedContent(currentContentAsHTML);
  };

  useEffect(() => {
    const contentBlocks = convertFromHTML(content);

    const contentState = ContentState.createFromBlockArray(
      contentBlocks.contentBlocks,
      contentBlocks.entityMap
    );

    setEditorState(EditorState.createWithContent(contentState));
  }, [content]);

  return (
    <div className='comment-container p-2 border rounded-md'>
      <Editor
        editorState={editorState}
        onEditorStateChange={handleEditorChange}
        wrapperClassName='wrapper-class'
        editorClassName='editor-class'
        toolbarClassName='toolbar-class'
        onClick={clearState}
      />
    </div>
  );


};

export default viewContent;

父组件

<viewContent
                      content={taskInfo.taskNote}
                      convertedContent={(convertedContent) =>
                        setTaskInfo((prevState) => ({
                          ...prevState,
                          taskNote: convertedContent,
                        }))
                      }
                    />

错误

您应该在 ViewContent 组件完全呈现后设置编辑器状态。更新您的组件如下:


...

useEffect(() => {
  const contentBlocks = convertFromHTML(content);

  const contentState = ContentState.createFromBlockArray(
    contentBlocks.contentBlocks,
    contentBlocks.entityMap
  );

  setEditorState(EditorState.createWithContent(contentState));
}, [content]);

...