保存数据
function saveContent() {
const content = editorState.getCurrentContent();
const rawObject = convertToRaw(content);
const draftRaw = JSON.stringify(rawObject); //<- save this to database
}
和检索:
setEditorState(()=> EditorState.push(
editorState,
convertFromRaw(JSON.parse(draftRaw)),
"remove-range"
););
它应该将您的数据保存为已保存。
提供的示例(可以正常工作)用于插入带有提及的新块,同时保存 entityMap。提及数据只是一个简单的对象 {id:.., name:.., link:... , avatar:...}
还有一件事:只初始化一次:换句话说,不要重新创建状态。
const [editorState, setEditorState] = useState(() => EditorState.createEmpty() );
然后填充类似的内容:
useEffect(() => {
try {
if (theDraftRaw) {
let mtyState = EditorState.push(
editorState,
convertFromRaw(JSON.parse(theDraftRaw)),
"remove-range"
);
setEditorState(mtyState);
} else editorClear();
} catch (e) {
console.log(e);
// or some fallback to other field like text
}
}, [theDraftRaw]);
const editorClear = () => {
if (!editorState.getCurrentContent().hasText()) return;
let _editorState = EditorState.push(
editorState,
ContentState.createFromText("")
);
setEditorState(_editorState);
};