javascript – React和Draft.js – convertFromRaw无效

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

任何帮助是极大的赞赏!

解决方法

似乎MongoDB / Mongoose不喜欢ContentState中的原始内容.在将数据发送到数据库之前将数据转换为字符串可以解决问题:

将ContentState保存到数据库

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

使用来自DB的数据

constructor(props) {
    super(props);
    const DbeditorState = convertFromraw(JSON.parse(this.props.blogPost.content));

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...