将旧数据保留在浏览器的本地存储中

时间:2019-07-04 10:18:44

标签: javascript reactjs local-storage

我想在单击按钮时保留我的数据。在此代码中,当前数据已成功存储在localStorage中,但是当下一个更新到达时,本地存储将被更新。我想存储两个数据而不会覆盖任何内容。

handleSubmit = (e,props) => {
      let localStorageArray = [];
      let myObj = {name : this.props.UserName,
                   Email : this.props.email,
                   Password : this.props.password,
                  Phone : this.props.phone};
      e.preventDefault();
      let key = 'Item 1';
      localStorage.setItem(key, JSON.stringify(myObj));
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
          change={...values}; 
          this.props.changeState(change);
        }
      });
    };

1 个答案:

答案 0 :(得分:2)

在更新之前,您应该首先获取存储中的内容。

在开始时声明key,然后通过影响其当前存储值来声明localStorageArray

handleSubmit = (e,props) => {
      let key = 'Item 1';
      // Retrieves your storage, or initializes it with an empty array if nothing is found.
      let localStorageArray = JSON.parse(localStorage.getItem(key) || '[]');
      let myObj = {name : this.props.UserName,
                   Email : this.props.email,
                   Password : this.props.password,
                  Phone : this.props.phone};

      e.preventDefault();

      // Pushes your new object.
      localStorageArray.push(myObj);

      // Updates your storage.
      localStorage.setItem(key, JSON.stringify(localStorageArray));

      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
          change={...values}; 
          this.props.changeState(change);
        }
      });
    };

下面是一个有效的示例:

// As the document is sandboxed, the following is to simulate the "localStorage".
const CustomStorage = { data: {} };

CustomStorage.getItem = (key) => CustomStorage.data[key];
CustomStorage.setItem = (key, value) => (CustomStorage.data[key] = value);
// ----------

const eAddBtn = document.querySelector('#btn-add'),
  eLogBtn = document.querySelector('#btn-log');
  
// logs the storage's data.
eLogBtn.addEventListener('click', () => console.log(JSON.parse(CustomStorage.getItem('_key') || '[]')));
  
// Adds an entry into the storage.
eAddBtn.addEventListener('click', () => {
  const eInputs = document.querySelectorAll('input'),
    storageKey = '_key',
    storageItem = JSON.parse(CustomStorage.getItem(storageKey) || '[]'),
    obj = {};
    
  Array.from(eInputs).forEach(eInput =>  obj[eInput.id] = eInput.value);
  
  storageItem.push(obj);
  
  CustomStorage.setItem(storageKey, JSON.stringify(storageItem));
});
<label for="name">
  <input id="name" type="text" placeholder="name">
</label>

<label for="age">
  <input id="age" type="number" min="0" placeholder="age">
</label>

<button id="btn-add">Add to storage</button>
<button id="btn-log">Log the storage</button>