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

如何将API返回的数据设置为Draft.js中editorState的初始状态

问题根因

  • 时序问题:你将editorState的初始化逻辑放在了useState的初始回调中,该逻辑仅会在组件第一次挂载时执行一次。如果组件首次渲染时,API请求还未完成,props.comment是初始的空值、undefined或占位内容,就会用错误的初始值创建内容状态,后续props.comment拿到接口返回的正确数据后,useState也不会重新执行初始化逻辑,自然无法渲染内容。你本地测试时用的是静态写死的变量,组件首次渲染就有完整数据,所以可以正常展示。
  • 接口返回内容转义:部分后端接口会自动转义HTML特殊字符,实际返回的是<p>Hello world...</p>这类转义后的字符串,不是原生HTML标签,convertFromHTML无法正常识别解析。
  • 你给出的示例HTML本身存在标签未闭合问题(<strong>结束标签写成了开始标签),如果实际接口返回的内容也存在类似HTML语法错误,也会导致解析失败。

修复方案

新增useEffect监听comment的变化,每次comment更新时重新生成内容状态并更新编辑器:

const ViewTaskComment = ({ comment }) => {
  const [editorState, setEditorState] = useState(() =>
    // 初始默认给空内容状态即可
    EditorState.createEmpty()
  );

  // 监听comment变化,动态更新编辑器内容
  useEffect(() => {
    if (!comment) return;
    // 可选:处理接口返回的HTML转义问题
    const unescapedComment = comment.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
    const contentBlocks = convertFromHTML(unescapedComment);
    const contentState = ContentState.createFromBlockArray(
      contentBlocks.contentBlocks,
      contentBlocks.entityMap
    );
    setEditorState(EditorState.createWithContent(contentState))
  }, [comment])

  const handleEditorChange = (state) => {
    setEditorState(state);
  };

  return (
    <div className='comment-container p-2 border rounded-md'>
      <Editor
        editorState={editorState}
        onEditorStateChange={handleEditorChange}
        wrapperClassName='wrapper-class'
        editorClassName='editor-class'
        toolbarClassName='toolbar-class'
        // 如果只是展示评论不需要编辑,建议加readOnly属性提升性能
        readOnly
      />
    </div>
  );
};

export default ViewTaskComment;

内容的提问来源于stack exchange,提问作者rSeeker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:15:08