小编典典

React&Draft.js-convertFromRaw不起作用

reactjs

我正在使用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

任何帮助是极大的赞赏!


阅读 453

收藏
2020-07-22

共1个答案

小编典典

似乎MongoDB / Mongoose不喜欢ContentState中的原始内容。在将数据发送到数据库之前将数据转换为String可以达到以下目的:

将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
    )};
}
2020-07-22