如何解决不显示来自 localStorage 的数据
我在我的项目中使用 ReactJs,并且我使用的是富文本编辑器,当我在内容 aria 中写一些东西时,我可以将数据保存在 localStorage 中,但是当我想在内容正文中保存数据时刷新整个页面后,它没有在内容咏叹调中显示数据,但我已成功将数据保存在 localStorage 中
不知道哪里出了问题
我试过这样:
const blogFromLS = () => {
if (typeof window === "undefined") {
return false;
}
if (localStorage.getItem("blog")) {
return JSON.parse(localStorage.getItem("blog"));
} else {
return false;
}
};
const [body,setBody] = useState({
editorState: EditorState.createEmpty(),blogFromLS: blogFromLS(),});
const { editorState } = body;
const onEditorStateChange = (editorState) => {
setBody({ editorState });
formData.set(
"body",draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
if (typeof window !== "undefined") {
localStorage.setItem(
"blog",JSON.stringify(
draftToHtml(convertToRaw(editorState.getCurrentContent()))
)
);
}
};
<div className="form-group">
<Editor
className="editorCustom"
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={onEditorStateChange}
placeholder="write something..."
// onChange={handleBody}
// value={body}
/>
</div>
请提出任何建议。
解决方法
您已接近目标。
您必须调整的是初始化编辑器状态的方式。您必须在初始化编辑器组件期间传递您存储在 localStorage 中的状态。为此,您必须使用 EditorState.createWithContent
静态方法。
const [editorState,setEditorState] = useState({
editorState: blogFromLS()
? EditorState.createWithContent(blogFromLS())
: EditorState.createEmpty()
});
此外,您似乎不需要使用 draftToHtml
,因为我们需要保存原始内容状态,而不是 html 或其他内容。
这是完整的解决方案:
import "./styles.css";
import { Editor,EditorState,convertToRaw,convertFromRaw } from "draft-js";
import "draft-js/dist/Draft.css";
import { useState } from "react";
const blogFromLS = () => {
if (typeof window === "undefined") {
return false;
}
if (localStorage.getItem("blog")) {
return convertFromRaw(JSON.parse(localStorage.getItem("blog")));
} else {
return false;
}
};
export default function App() {
const [editorState,setEditorState] = useState({
editorState: blogFromLS()
? EditorState.createWithContent(blogFromLS())
: EditorState.createEmpty()
});
const onChange = (editorState) => {
setEditorState({ editorState });
if (typeof window !== "undefined") {
localStorage.setItem(
"blog",JSON.stringify(convertToRaw(editorState.getCurrentContent()))
);
}
};
return (
<div className="App">
<Editor editorState={editorState.editorState} onChange={onChange} />
</div>
);
}
该代码段也可在 sandbox 中找到。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。