javascript - React & Draft.js - convertFromRaw 不工作

标签 javascript reactjs draftjs

我正在使用 Draft.js 来实现文本编辑器。我想将编辑器的内容保存到数据库中,稍后检索它并再次将其注入(inject)编辑器中,例如重新访问编辑器页面时。

首先,这些是相关的导入

import { ContentState, EditorState, convertToRaw, convertFromRaw } from 'draft-js';

我如何将数据保存到数据库(位于父组件中)

saveBlogPostToStore(blogPost) {
    const JSBlogPost = { ...blogPost, content: convertToRaw(blogPost.content.getCurrentContent())};
    this.props.dispatch(blogActions.saveBlogPostToStore(JSBlogPost));
}

现在,当我检查数据库时,我得到以下对象:

[{"_id":null,"url":"2016-8-17-sample-title","title":"Sample Title","date":"2016-09-17T14:57:54.649Z","content":{"blocks":[{"key":"4ads4","text":"Sample Text Block","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[]}]},"author":"Lukas Gisder-Dubé","__v":0,"tags":[]}]

到目前为止,我想一切都很好,我尝试了一些其他的东西,数据库中的对象肯定被转换了。例如,当我在不调用 convertToRaw() 方法的情况下保存内容时,会有更多的字段。

将数据设置为新的 EditorState

从数据库中取出数据并设置为EditorState,我也尝试了很多。以下是我的最佳猜测:

constructor(props) {
    super(props);
    const DBEditorState = this.props.blogPost.content;
    console.log(DBEditorState); // logs the same Object as above
    this.state = { ...this.props.blogPost, content: EditorState.createWithContent(
        convertFromRaw(DBEditorState)
    )};
}

渲染组件时出现以下错误:

convertFromRawToDraftState.js:38 Uncaught TypeError: Cannot convert undefined or null to object

非常感谢任何帮助!

最佳答案

似乎 MongoDB/Mongoose 不喜欢来自 ContentState 的原始内容。在将数据发送到数据库之前将数据转换为字符串就可以达到目的:

将 ContentState 保存到数据库

    saveBlogPostToStore(blogPost) {
    const JSBlogPost = { ...blogPost, content: JSON.stringify(convertToRaw(blogPost.content.getCurrentContent()))};
    this.props.dispatch(blogActions.saveBlogPostToStore(JSBlogPost));
}

使用数据库中的数据

constructor(props) {
    super(props);
    const DBEditorState = convertFromRaw(JSON.parse(this.props.blogPost.content));

    this.state = { ...this.props.blogPost, content: EditorState.createWithContent(
        DBEditorState
    )};
}

关于javascript - React & Draft.js - convertFromRaw 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548380/

相关文章:

javascript - 是否可以使用 HTML、CSS 和 Javascript 构建 LibreOffice 侧边栏插件

html - 小型设备上轮播中的按钮封面图像

javascript - 如何获取当前光标在draft.js中的位置?

reactjs - Draft.js——获取 html 格式的编辑器内容

javascript - React + MobX,用户认证,渲染错误

javascript - DraftJs 创建尽可能简单的自定义 block

javascript - Canvas 中的动画栏

javascript - 如何在 React 中打印 JavaScript new Date()?

javascript - 此 slider 中加载的随机图像

javascript - react native : How to create text with fixed character widths