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

React Draft Wysiwyg编辑器始终显示undefined,求定位代码问题

问题原因&修正方案

你代码里主要存在3个问题:

  1. 数据取值错误:你声明的apiResponse初始值是数组,接口返回的也是对象数组,直接访问apiResponse.description相当于访问数组本身的description属性,必然返回undefined,正确取值应该先取数组对应元素,比如apiResponse[0]?.description。
  2. 富文本状态未同步接口数据:useState的初始化逻辑只会在组件第一次渲染时执行一次,第一次渲染时接口请求还没完成,生成的editorState本身就是基于undefined创建的空状态。后续接口拿到数据后没有对应逻辑更新editorState,所以编辑器内容不会变化。
  3. Editor组件属性冲突:同时传入了editorState和defaultEditorState两个属性,受控模式下只需要保留editorState即可,重复传值会导致状态更新异常。

修正后代码示例

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

// 接口返回数据状态
const [apiResponse, setApiResponse] = useState([]);
// 编辑器状态初始设为空即可
const [editorState, setEditorState] = useState(() => 
  EditorState.createEmpty()
);

// 接口请求逻辑不变
useEffect(() => {
    // 你的axios请求逻辑
    axios.get('你的接口地址').then(data => {
        setApiResponse(data.data.payload);
    })
},[]);

// 新增监听apiResponse变化的useEffect,同步更新编辑器内容
useEffect(() => {
    // 数组有值再处理逻辑
    if(apiResponse.length > 0) {
        const desc = apiResponse[0].description;
        const blocksFromHTML = convertFromHTML(desc || '');
        const contentState = ContentState.createFromBlockArray(
            blocksFromHTML.contentBlocks,
            blocksFromHTML.entityMap
        );
        setEditorState(EditorState.createWithContent(contentState))
    }
}, [apiResponse])

const onEditorStateChange = (newEditorState) => {
    setEditorState(newEditorState);
    // 如需实时获取富文本html内容,可在这里存到其他状态
    // const htmlContent = draftToHtml(convertToRaw(newEditorState.getCurrentContent()));
};

// 渲染Editor组件去掉defaultEditorState属性
return (
    <Editor
        toolbarClassName="toolbarClassName"
        wrapperClassName="ChannelDesscription"
        editorClassName="editorClassName"
        editorState={editorState}
        onEditorStateChange={onEditorStateChange}
    />
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:54:04