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

标签 reactjs lexical

这是我第一次在 stackoverflow 上提问,但我在这个问题上被困了太多天了。

我的问题,如何将initialConfig.editorState更改为我刚刚保存在数据库中的stringifiedEditorState?

到目前为止,我正在使用 Lexical,这是一个带有 React/Next.js 的 Facebook 文本编辑器。我能够创建一个编辑器并将其作为 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
   }
}

我希望能够使用新的只读词法编辑器读取保存到 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更改为我刚刚保存在数据库中的stringifiedEditorState?

最佳答案

编辑器初始化

您只需通过 editorState 键将序列化字符串传递到编辑器的初始状态即可。

例如:

// your config
const editorConfig = {
  // the rest of your config...
  editorState: editorStateJSONString,
};

// inside your return statement
<LexicalComposer initialConfig={editorConfig}>
   {/* Your plugins */}
</LexicalComposer>

需要注意的是:

Note that Lexical uses initialConfig.editorState only once (when it's being initialized) and passing different value later won't be reflected in editor

来自:https://lexical.dev/docs/concepts/editor-state

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

编辑器初始化后

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

Another way to set state is setEditorState method, which replaces current state with the one passed as an argument.

例如:

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

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

更多详情请参阅:https://lexical.dev/docs/concepts/editor-state

关于reactjs - 将词汇数据发送到服务器并使用新的词汇组件读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73042976/

相关文章:

reactjs - 如何使用键盘 Tab 键聚焦于 Material UI Link(不使用组件 ="button")

javascript - 尝试以设定的时间间隔在 nivo 中创建图表

iphone - 词法或预处理器问题错误(未找到 UIKit/UIKit.h 文件)

javascript - 通过 PluralSight 进行 React 教程 - Prop 未定义

reactjs - 渲染期间加载屏幕(异步渲染)

javascript - 使用 polyglot.js 翻译带有标记的文本

xcode - 如何将我的 .m 文件更改为 .mm 文件?

java - 词法语法和句法语法有什么区别?

javascript - 需要帮助理解 Javascript 中的(词法)变量范围

c - 使用词法进行词法分析