如何使用 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>
)
}