【问题标题】:Is there a way to make an async request inside a lexical editor update in react?有没有办法在词法编辑器更新中发出异步请求?
【发布时间】:2023-01-20 05:37:25
【问题描述】:

我在 React 中使用 Lexical 作为富文本编辑器包。它有一种选择突出显示的文本并更新它的方法。当我使用一些预定义的字符串更新它时,这工作正常,但我想将突出显示的文本发送到 API,然后使用响应更新屏幕上的文本,并且函数的异步性质似乎导致了问题。下面的editorLexicalEditor对象。

这很好用:

editor.update( () => {
  const selection = $getSelection();
  const textContent = selection?.getTextContent();
  selection?.insertText("Some text...");
  $setSelection(null);
});

这不起作用:

editor.update( async () => {
  const selection = $getSelection();
  const textContent = selection?.getTextContent();
  const textApiResponse = await fetchResponse(textContent);
  selection?.insertText(textApiResponse);
  $setSelection(null);
});

收到的错误是:

Uncaught (in promise) Error: Unable to find an active editor state. State helpers or node methods can only be used synchronously during the callback of editor.update() or editorState.read().

有没有办法达到目的?

【问题讨论】:

    标签: reactjs lexicaljs


    【解决方案1】:

    我能够通过将文本选择从更新中提取出来,执行请求,然后进行更新来解决这个问题。它可能需要禁用交互性,但这似乎是一条前进的道路。欢迎任何替代方案。

    async () => {
      const textContent = editor.getEditorState().read(() => $getSelection()?.getTextContent());
      const textApiResponse = await fetchResponse(textContent);
      editor.update(() => {
        const selection = $getSelection();
        selection?.insertText(textContent);
        $setSelection(null);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 2019-08-16
      • 1970-01-01
      • 2019-07-26
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多