反应& Draft.js - convertFromRaw不起作用

时间:2016-09-17 15:12:10

标签: javascript reactjs draftjs

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

首先,这些是相关的进口

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

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:13)

似乎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
    )};
}
相关问题