如何使用 React 保存和加载 Markdown?



我是 React 的新手。我有一个任务,构建一个集成了块堆栈IDMarkdown编辑器

我正在尝试将内容保存到 JSON 文件中,然后在编辑器中再次加载它,但似乎无法将该 JSON 文件加载回编辑器。

下面是一些代码:

import MDEditor from '@uiw/react-md-editor';
<MDEditor
onChange={e=>this.updateMarkdown(e)}
value={this.state.markdown}
/>

<button
onClick={e => this.saveNewText(e)}>
Submit Changes
</button>
updateMarkdown(editor, data, value) {
this.setState({ markdown: value})
}

saveNewText() {
const { userSession } = this.props
let currentDocument = this.state.currentDocument
let newDocument = {
md: this.state.markdown,
created_at: Date.now()
}
const options = { encrypt: true }
userSession.putFile('Document.json', JSON.stringify(newDocument), options)
.then(() => {
this.setState({
currentDocument:newDocument
})
})
}
loadNewText() {
const { userSession } = this.props
const options = { decrypt: true }
userSession.getFile('Document.json', options)
.then((file) => {
var docFile = JSON.parse(file || '[]');
this.setState({
currentDocument:docFile,
markdown:docFile.md
});
})
}
componentWillMount() {
const { userSession } = this.props
this.setState({
person: new Person(userSession.loadUserData().profile),
username: userSession.loadUserData().username
});
this.loadNewText();

react-blockstack 包为 React 提供了一个useFile钩子,可以将内容持久化到 Blockstack Gaia 存储中:

const [document, setDocument] = useFile('Document.json')

这将替换除文本和 JSON 之间的转换之外的大部分代码。

最新更新