如何持久化TipTap编辑器数据,避免页面刷新后丢失?
解决TipTap编辑器内容刷新后持久化的问题
核心问题原因
localStorage仅支持存储字符串类型数据,直接存入JSON对象会被隐式转为"[object Object]",导致读取时无法还原成有效内容。必须通过**序列化(对象转字符串)和反序列化(字符串转对象)**处理JSON内容才能正常存储。
具体实现方案
1. 初始化与实时保存逻辑
组件挂载时从localStorage读取并反序列化内容作为编辑器初始值,编辑器内容更新时实时序列化存入localStorage:
import { useState, useEffect } from 'react'; import { Editor, EditorContent } from '@tiptap/react'; import StarterKit from '@tiptap/starter-kit'; const PersistentTipTapEditor = () => { // 初始化状态:优先读取localStorage,无数据则用默认空文档结构 const [editorContent, setEditorContent] = useState(() => { const saved = localStorage.getItem('tiptap-editor-content'); return saved ? JSON.parse(saved) : { type: 'doc', content: [{ type: 'paragraph' }] }; }); const editor = new Editor({ extensions: [StarterKit], content: editorContent, // 内容更新时同步保存到localStorage和状态 onUpdate: ({ editor }) => { const contentJson = editor.getJSON(); localStorage.setItem('tiptap-editor-content', JSON.stringify(contentJson)); setEditorContent(contentJson); }, }); // 组件卸载时销毁编辑器实例 useEffect(() => { return () => editor.destroy(); }, [editor]); return <EditorContent editor={editor} />; }; export default PersistentTipTapEditor;
2. 边界情况处理
- 首次加载页面时,若localStorage无存储内容,需传入TipTap可识别的合法空文档结构(如示例中的空段落),避免编辑器初始化报错。
- 需要清除已保存内容时,调用
localStorage.removeItem('tiptap-editor-content')即可。
关键代码说明
JSON.stringify(editor.getJSON()):将TipTap返回的JSON内容转为字符串,适配localStorage的存储要求。JSON.parse(localStorage.getItem('tiptap-editor-content')):读取存储的字符串并转回TipTap可解析的JSON对象。onUpdate回调:确保内容修改后立即保存,避免页面意外刷新导致内容丢失。
内容的提问来源于stack exchange,提问作者lakhera24
相关产品推荐
相关产品推荐

