问题描述
我正在使用Draft.js来实现文本编辑器。我想将编辑器的内容保存到数据库中,然后将其检索并再次将其注入编辑器,例如当重新访问编辑页面时。
I'm using Draft.js to implement a text editor. I want to save the content of the editor to a DB and later retrieve it and inject it in an editor again, e.g. when revisiting the editor page.
首先,这些是相关的进口
import { ContentState, EditorState, convertToRaw, convertFromRaw } from 'draft-js';
我如何将数据保存到数据库(位于父组件中)
saveBlogPostToStore(blogPost) {
const JSBlogPost = { ...blogPost, content: convertToRaw(blogPost.content.getCurrentContent())};
this.props.dispatch(blogActions.saveBlogPostToStore(JSBlogPost));
}
现在当我检查数据库时,我得到以下对象:
Now when I check the DB, I get the following Object:
[{"_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()方法的情况下保存内容时,还有更多字段。
So far so good I guess, I tried some other stuff and the Object in the Database is definitely converted. For example, when I save the content without calling the convertToRaw()-method, there are a lot more fields.
将数据设置为新的EditorState
要从数据库中检索数据并将其设置为EditorState,我也尝试了很多。以下是我最好的猜测:
To retrieve the Data from the DB and set it as EditorState, I also tried a lot. The following is my best guess:
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)
)};
}
渲染组件时出现以下错误:
When rendering the component i get the following error:
convertFromRawToDraftState.js:38 Uncaught TypeError: Cannot convert undefined or null to object
非常感谢任何帮助!
推荐答案
似乎MongoDB / Mongoose没有'喜欢ContentState的原始内容。在将数据发送到数据库之前将数据转换为字符串可以解决问题:
Seems that MongoDB/Mongoose didn't like the raw content from the ContentState. Converting the data to a String before sending it to the DB did the trick:
将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
)};
}
这篇关于反应& Draft.js - convertFromRaw不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!