将词法数据发送到服务器,并使用新的词法组件读取它



这是我第一次用stackoverflow问问题,但是我被这个问题困了太多天了

我的问题,我怎么能改变initialConfig。editorState到我保存在数据库中的stringifiedEditorState ?

到目前为止,我正在使用Lexical,一个带有React/Next.js的Facebook文本编辑器。我能够创建一个编辑器并将其保存到我的mongodb数据库作为JSON字符串。
{
"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
}
}

我希望能够读取Json值,我保存到我的mongodb数据库与一个新的只读词法编辑器。

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到我保存在数据库中的stringifiedEditorState ?

编辑器初始化

您可以简单地通过editorState键将序列化字符串传递到编辑器的初始状态。

例如:

// your config
const editorConfig = {
// the rest of your config...
editorState: editorStateJSONString,
};
// inside your return statement
<LexicalComposer initialConfig={editorConfig}>
{/* Your plugins */}
</LexicalComposer>

注意:

注意Lexical使用initialConfig。只有一次editorState(当它为初始化)和稍后传递不同的值不会反映在编辑器

从:https://lexical.dev/docs/concepts/editor-state

因此,这取决于初始化编辑器的时间和检索数据库数据的时间。

编辑器初始化后

初始化后可以使用setEditorState来更新状态:

另一种设置状态的方法是setEditorState方法,它代替作为参数传递的当前状态

例如:

const editorState = editor.parseEditorState(editorStateJSONString);
editor.setEditorState(editorState);

: https://lexical.dev/docs/concepts/editor-state updating-state

详细信息请参见:https://lexical.dev/docs/concepts/editor-state

最新更新