javascript - 无法在 Draft.js 中设置 editorState (它看起来不可变,但没有错误)

标签 javascript reactjs draftjs

我已使用convertToRaw 将内容保存到数据库中,我正尝试将其加载回draft.js 编辑器以使用户能够重新编辑内容。

draft.js 编辑器包含在 react-modal 中当用户单击内容上的“编辑”时显示的基于组件。这很重要,因为模态框(和编辑器)不会重新实例化,它们只是显示和隐藏。

编辑器在 (ES6) 类构造函数中启动一次,只需使用:

this.state = {editorState: EditorState.createEmpty()}

当用户单击“编辑”时,我从数据库加载原始内容,然后我尝试使用以下多种变体将原始内容加载到编辑器中:

const contentState = convertFromRaw(rawContent)
const newEditorState = EditorState.push(this.state.editorState, contentState);
this.setState({editorState: newEditorState})

虽然 newEditorState 显然包含正确的内容,但 this.setState({editorState: newEditorState}) 似乎对组件(或编辑器)的状态没有任何影响。

我该如何为编辑器设置新状态?谢谢!

更新 经过进一步调查,显然只是 this.setState({editorState: newEditorState}) 只是编辑器组件失败了。

我通过设置测试状态属性并成功更新它来测试它,而 editorState 保持不变。

为了充分测试这一点,在我的构造函数中,我使用测试值初始化了状态:

this.state = { 
    editorState:EditorState.createWithContent(ContentState.createFromText('Hello')),
    testVal: 'Test Val 1'
}

然后我编写了一些测试代码来展示 setState 如何适用于我的测试值,但不适用于 Draft.js editorState:

const newEditorState = EditorState.createWithContent(ContentState.createFromText('Goodbye'))
console.log('Before setState')
console.log('newEditorState: ' + newEditorState.getCurrentContent().getPlainText());
console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
console.log('testVal: ' + this.state.testVal);

this.setState({editorState: newEditorState, testVal: 'Test Val 2'}, function(){
    console.log('After setState')
    console.log('editorState: ' + this.state.editorState.getCurrentContent().getPlainText());
    console.log('testVal: ' + this.state.testVal);
});

控制台输出如下所示:

Before setState
    newEditorState: Goodbye
    editorState: Hello
    testVal: Test Val 1
After setState
    editorState: Hello
    testVal: Test Val 2

我不明白为什么在 testVal 更新时,draft.js editorState 没有更新?

最佳答案

我在我的项目中使用了以下内容

const blocks = convertFromRaw(props.rawBlocks);
editorState = EditorState.createWithContent(blocks, null);

关于javascript - 无法在 Draft.js 中设置 editorState (它看起来不可变,但没有错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710215/

相关文章:

draftjs - 将目标 ="_blank"添加到 Draft.js 内容中的所有链接

javascript - 在 Draft JS 中实现自动完成但没有像 "trigger"这样的 "@"

javascript - Google Analytics 同时向不同域的多个配置文件报告

javascript - 从应用程序组件中清除/删除 Angular 应用程序服务变量依赖项的使用

reactjs - 如何在 typescript 中导入 react-cookie

reactjs - Draftjs 如何启动内容编辑器

javascript - 想要使用 react cra 使动态页面可索引

javascript - 在 SPA 中堆叠页面,是好主意还是坏主意?

javascript - "Cannot read property ' 在 redux store 中输入 ' of undefined"用于外部包中定义的操作

reactjs - Typescript:推断作为参数传递给另一个函数的回调函数的参数