0

如何使用 React onEffect 挂钩轻松设置整个 SlateJS 编辑器值?

初始编辑器值是在创建 useState 钩子时设置的,但是,我想在之后设置一个新的初始值。

目前,我们可以通过使用 Transform 删除所有元素然后插入新元素来做到这一点,但这是一种更简单的方法,比如覆盖所有?我似乎在 SlateJS 文档中找不到它。

保存到数据库 slatejs 示例不起作用,但这是我的设置功能

const App = () => {
  const editor = useMemo(() => withReact(createEditor()), [])
  // Update the initial content to be pulled from Local Storage if it exists.
  const [value, setValue] = useState(
    [
      {
        type: 'paragraph',
        children: [{ text: 'A line of text in a paragraph.' }],
      },
    ]
  )

  useEffect(() => {
    // Get saved SlateJS text from local storage
    const savedSlateTextData = getSavedSlateJSData(localStorage)

    // In theory, this should set the SlateJS values to the loaded data
    // In practice, I think because the editor is immutable outside transform, it don't work 
    setValue(savedSlateTextData)
  }, [])

  return (
    <Slate
      editor={editor}
      value={value}
      onChange={value => {
        setValue(value)
        const isAstChange = editor.operations.some(
          op => 'set_selection' !== op.type
        )
        if (isAstChange) {
          // Save the value to Local Storage.
          const content = JSON.stringify(value)
          localStorage.setItem('content', content)
        }
      }}
    >
      <Editable />
    </Slate>
  )
}
4

1 回答 1

1

不要以为我想要的是可能的,你需要删除所有的节点,然后插入新的节点。

不确定您是否可以使用 match 而不是一堆 for 循环,也许。

  // Get initial total nodes to prevent deleting affecting the loop
  let totalNodes = editor.children.length

  // No saved content, don't delete anything to prevent errors
  if (savedSlateJSContent.length <= 0) {
      return
  }

  // Remove every node except the last one
  // Otherwise SlateJS will return error as there's no content
  for (let i = 0; i < totalNodes - 1; i++) {
      console.log(i)
      Transforms.removeNodes(editor, {
          at: [i],
      })
  }

  // Add content to SlateJS
  for (const value of savedSlateJSContent {
      Transforms.insertNodes(editor, value, {
          at: [editor.children.length],
      })
  }

  // Remove the last node that was leftover from before
  Transforms.removeNodes(editor, {
      at: [0],
  })
于 2022-02-22T01:38:35.000 回答