【问题标题】:Draftjs how to save input data to LocalStorage without overwriting the previous data?Draftjs如何将输入数据保存到LocalStorage而不覆盖以前的数据?
【发布时间】:2020-08-20 02:45:19
【问题描述】:

我正在使用 Draftjs 富文本编辑器将我的文本输入保存到本地存储。现在,我的程序能够接受文本输入,当我点击保存时,它会将文本输入保存到我的本地存储中。代码:

import React from "react";
import { Editor, EditorState, convertToRaw } from "draft-js";

class SaveData extends React.Component {
  constructor(props) {
    super(props);
    this.state = { editorState: EditorState.createEmpty() };
    this.onChange = (editorState) => this.setState({ editorState });
  }

  getContentAsRawJson() {
    const contentState = this.state.editorState.getCurrentContent();
    const raw = convertToRaw(contentState);
    return JSON.stringify(raw, null, 2);
  }
  saveContent() {
    const json = this.getContentAsRawJson();
    localStorage.setItem("savedContent", json);
  }

  render() {
    return (
      <div>
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
        <button onClick={this.saveContent.bind(this)}>Save Content</button>
        <pre>{this.getContentAsRawJson}</pre>
      </div>
    );
  }
}

export default SaveData;

The input from the text editor saved in local storage

但是,我需要 saveContent() 函数来不覆盖已保存在本地存储中的现有内容。 我想要实现的示例如下所示:

  • 我在文本编辑器中输入了一些文本,点击保存,文本被保存 在我的本地存储中。
  • 然后我在文本编辑器中添加一些新文本,点击保存,文本 与我之前的输入一起保存而不会覆盖它。
  • 将两个文本输入加载到文本编辑器中。

我相信我需要将状态保存到本地存储中的数组中,并且每当我按下保存时,它都会将新数据附加到数组的末尾。但我不知道如何实现这一目标。 任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs local-storage state draftjs


    【解决方案1】:

    当组件挂载或更新时,从localStorage 获取text(如果存在)并将其设置为内部状态。然后在文本更改和存储集上更新状态 localStorage 状态 text 的文本。

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2012-05-07
      • 2017-04-12
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      相关资源
      最近更新 更多