【发布时间】:2021-02-27 05:00:34
【问题描述】:
我正在尝试在我正在创建的博客应用程序中使用 Draft.js。将数据保存到数据库并将其取回时,一切似乎都很好,只是我似乎无法让 createWithContent 工作。
当我编写以下内容时,数据确实会保存到数据库中,因为我只是创建一个空编辑器,然后由用户更新并在 convertToRaw 之后发送到数据库。
const postDetails = useSelector((state) => state.postDetails);
const { loading, post, error } = postDetails;
const editorContent = EditorState.createEmpty();
const [editorState, setEditorState] = useState({ editorState: editorContent });
const handleEditorChange = (editorState) => { setEditorState({ editorState }) }
const submitHandler = (e) => {
e.preventDefault();
dispatch(
updatePost({
_id: id,
title,
image,
images,
paragraph: JSON.stringify(
convertToRaw(editorState.editorState.getCurrentContent())
),
})
);
};
<Editor
editorState={editorState.editorState}
onEditorStateChange={handleEditorChange}
/>
但是当我使用时
EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph)))
这是我真正想要的(用来自数据库的 post.paragrah 填写的段落),我收到以下错误:
引发了跨域错误。 React 无法访问 开发中的实际错误对象。
我以这种方式处理跨域:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
另外,当我使用 console.log(post.paragraph) 时,我确实得到了我的段落:
但我注意到,在收到我的段落之前我也得到了 2 个未定义,这可能是问题的一部分。
为了解决这个问题,我已经尝试了这两种方法:
const editorContent = post ?
EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph))) :
EditorState.createEmpty();
const [editorState, setEditorState] = useState({ editorState: editorContent });
还有这个:
const editorContent = await post.paragraph;
if (post.paragraph) {
res.send({ editorContent: EditorState.createWithContent(convertFromRaw(JSON.parse(post.paragraph))) });
} else {
res.send({ editorContent: EditorState.createEmpty()});
}
return editorContent;
})
const [editorState, setEditorState] = useState({ editorState: content });
我在网络上做了很多研究,但我没有成功地想出任何东西。 希望大家能帮忙。提前致谢
【问题讨论】:
-
devtools 的控制台或网络选项卡中应该有警告或错误,请检查它们并将该信息添加到您的问题中
-
您好 dieu,感谢您的帮助。我确实在我的问题中添加了错误:引发了跨域错误。 React 无法访问开发中的实际错误对象。这还不够吗?谢谢
-
在解析 JSON 时似乎发生了主要错误,记录您尝试解析的 json 字符串以查看它是否有效
-
如果是这种情况,只需将那部分代码包装在 if
if (post.paragraph) EditorState.createWithContent(...中,因为您没有指定获取帖子数据的位置和方式,我猜可能发生了一些异步操作 -
不,很遗憾。希望好心人来帮忙。我暂时使用降价作为临时替代方案。如果您找到解决问题的方法,请告诉我。谢谢
标签: reactjs mongodb redux text-editor cross-origin-read-blocking