如何将MongoDB存储的stringifiedEditorState设为Lexical编辑器初始状态?
这是我第一次在StackOverflow提问,该问题已困扰我多日。
我的问题:如何将initialConfig.editorState修改为刚存入MongoDB的stringifiedEditorState?
目前我在React/Next.js环境中使用Facebook推出的Lexical文本编辑器,已成功创建编辑器并将其状态以JSON字符串形式保存到MongoDB,示例数据如下:
{ "root": { "children": [ { "children": [ { "detail": 0, "format": 1, "mode": "normal", "style": "", "text": "Test", "type": "text", "version": 1 } ], "direction": "ltr", "format": "", "indent": 0, "type": "paragraph", "version": 1 } ], "direction": "ltr", "format": "", "indent": 0, "type": "root", "version": 1 } }
我希望用新的只读Lexical编辑器读取MongoDB中保存的该JSON值,现有代码如下:
function onChange(editorState: any) { editorState.read(() => { const stringifiedEditorState = JSON.stringify(editorState.toJSON()); setValue(stringifiedEditorState); }); } const initialConfig = { namespace: "editeurConfig", theme: editeurTheme, onError: onError, nodes: [ListNode, ListItemNode, AutoLinkNode, LinkNode], readOnly: true, editorState: null };
再次请教:如何将initialConfig.editorState修改为刚存入MongoDB的stringifiedEditorState?
要实现从MongoDB加载保存的编辑器状态到只读Lexical编辑器,按以下步骤操作:
解析保存的状态字符串
从MongoDB取出stringifiedEditorState后,用JSON.parse()将其转换为JavaScript对象。转换为Lexical可识别的EditorState
导入Lexical的createEditorState方法,将解析后的JSON对象转换成编辑器能直接使用的EditorState实例。配置initialConfig
将生成的EditorState实例赋值给initialConfig.editorState即可。
基础代码示例
import { createEditorState } from 'lexical'; // 假设已从MongoDB获取到保存的字符串 const stringifiedEditorState = "你的MongoDB中存储的JSON字符串"; // 解析并转换为EditorState const parsedState = JSON.parse(stringifiedEditorState); const loadedEditorState = createEditorState(parsedState); // 更新initialConfig const initialConfig = { namespace: "editeurConfig", theme: editeurTheme, onError: onError, nodes: [ListNode, ListItemNode, AutoLinkNode, LinkNode], readOnly: true, editorState: loadedEditorState // 替换为加载后的状态 };
Next.js客户端组件完整示例
如果需要异步从接口获取MongoDB数据,可在组件中用useEffect处理:
import { useState, useEffect } from 'react'; import { createEditorState } from 'lexical'; import { LexicalComposer } from '@lexical/react'; export default function ReadOnlyEditor() { const [editorState, setEditorState] = useState(null); useEffect(() => { async function fetchSavedState() { // 调用接口获取MongoDB中保存的编辑器状态 const res = await fetch('/api/get-editor-state'); const data = await res.json(); // 解析并转换为EditorState const parsedState = JSON.parse(data.stringifiedState); setEditorState(createEditorState(parsedState)); } fetchSavedState(); }, []); if (!editorState) return <div>加载中...</div>; const initialConfig = { namespace: "editeurConfig", theme: editeurTheme, onError: onError, nodes: [ListNode, ListItemNode, AutoLinkNode, LinkNode], readOnly: true, editorState: editorState }; return ( <LexicalComposer initialConfig={initialConfig}> {/* 渲染你的编辑器UI组件 */} </LexicalComposer> ); }
注意:确保已导入所有在保存状态时用到的节点类型(比如ListNode、ListItemNode等),否则加载状态时可能出现节点无法识别的错误。
内容的提问来源于stack exchange,提问作者Samuel Duhaime-Morissette

