¿Cómo configurar fácilmente el valor completo del editor SlateJS usando el gancho React onEffect?
El valor inicial del editor se establece al crear el enlace useState, sin embargo, quiero establecer un nuevo valor inicial después.
Actualmente, podemos hacer eso eliminando todos los elementos con Transform y luego insertando nuevos elementos, pero ¿es una forma más fácil, como anular todo? Parece que no puedo encontrarlo en los documentos de SlateJS.
Guardar en la base de datos slatejs ejemplo No funciona, pero es cómo funciona mi configuración
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> ) }No crea que lo que quiero es posible: debe eliminar todos los nodos y luego insertar otros nuevos.
No estoy seguro de si podría usar match en lugar de un montón de bucles for, tal vez.
// 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: [totalNodes-i-1], }); } // 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], });Esta es la forma más limpia que se me ocurrió de usar lo que está disponible a través de Slate
const INITIAL_SLATE_VALUE = [ { type: 'paragraph', children: [{ text: 'A line of text in a paragraph.' }], }, ] const [value, setValue] = useState(INITIAL_SLATE_VALUE) // Delete all entries leaving 1 empty node Transforms.delete(editor, { at: { anchor: Editor.start(editor, []), focus: Editor.end(editor, []), }, }) // Removes empty node Transforms.removeNodes(editor, { at: [0], }) // Insert array of children nodes Transforms.insertNodes( editor, value )