如何在React中保存和加载Markdown?

4

我是React的新手。我的任务是构建一个集成了Blockstack ID的Markdown编辑器

我尝试将内容保存到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();
1个回答

1

react-blockstack包为React提供了一个useFile钩子,用于在Blockstack Gaia存储中持久化内容:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接