draft-js加载后端存储的富文本数据无显示无报错如何解决?
问题修复方案
代码存在以下多处逻辑错误,按顺序修改即可正常加载后端返回内容:
- React组件命名不规范
React自定义组件必须以大写字母开头,将viewContent重命名为ViewContent,父组件调用时同步修改为<ViewContent />,否则React会将其识别为原生HTML标签,不会执行组件内部逻辑。
- React组件命名不规范
- 缺失依赖引入、参数接收
- 组件顶部补充引入React相关hooks和draft-js缺失方法:
import React, { useState, useEffect } from 'react'; import { EditorState, ContentState, convertFromHTML, convertToRaw // 补充缺失的convertToRaw引入 } from 'draft-js'; - 组件参数解构时补充接收
convertedContent属性:const ViewContent = ({ content, convertedContent }) => {
- 编辑器状态初始化异常
首次渲染时editorState为undefined,直接传给Editor组件会导致渲染失败,修改state初始化逻辑:
- 编辑器状态初始化异常
const [editorState, setEditorState] = useState(() => EditorState.createEmpty());
- 内容转换逻辑错误
你保存内容时用了JSON.stringify包裹HTML字符串,后端返回的taskInfo.taskNote实际是带双引号的JSON字符串,直接传给convertFromHTML无法解析,需要先做JSON解析,修改useEffect逻辑:
- 内容转换逻辑错误
useEffect(() => { if (!content) return; // 先解析外层JSON包裹,拿到原始HTML内容 const rawHtml = typeof content === 'string' ? JSON.parse(content) : content; const contentBlocks = convertFromHTML(rawHtml); const contentState = ContentState.createFromBlockArray( contentBlocks.contentBlocks, contentBlocks.entityMap ); setEditorState(EditorState.createWithContent(contentState)); }, [content]);
- 编辑状态获取逻辑错误
handleEditorChange中刚调用setEditorState,React状态还未更新,不能直接用当前的editorState取值,改为使用传入的新state参数:
- 编辑状态获取逻辑错误
const handleEditorChange = (state) => { setEditorState(state); const currentContentAsHTML = JSON.stringify( draftToHtml(convertToRaw(state.getCurrentContent())) ); convertedContent(currentContentAsHTML); };
- 清空逻辑无效
clearState仅创建了空内容对象,未更新编辑器状态,修改为:
- 清空逻辑无效
const clearState = () => { setEditorState(EditorState.createWithContent(ContentState.createFromText(''))); };
内容的提问来源于stack exchange,提问作者rSeeker
相关产品推荐
相关产品推荐

