我正在使用Draft.js来实现文本编辑器。我希望将编辑器的内容保存到DB中,然后检索它并将其再次注入编辑器中,例如在重新访问编辑器页面时。
首先,这些是相关的导入
import { ContentState, EditorState, convertToRaw, convertFromRaw } from 'draft-js';如何将数据保存到数据库(位于父组件中)
saveBlogPostToStore(blogPost) {
const JSBlogPost = { ...blogPost, content: convertToRaw(blogPost.content.getCurrentContent())};
this.props.dispatch(blogActions.saveBlogPostToStore(JSBlogPost));
}现在,当我检查DB时,我得到了以下对象:
[{"_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()-method的情况下保存内容时,有更多的字段。
将数据设置为新的EditorState
为了从DB检索数据并将其设置为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任何帮助都是非常感谢的!
发布于 2016-09-18 13:22:31
似乎MongoDB/Mongoose不喜欢ContentState中的原始内容。在将数据发送到DB之前,将数据转换为字符串可以达到以下目的:
将ContentState保存到DB
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
)};
}https://stackoverflow.com/questions/39548380
复制相似问题