在本地存储中保存多个结果

时间:2019-12-16 15:27:01

标签: javascript reactjs local-storage

我需要在本地存储中保存一个或多个仿真数据

公证道具=数据

输入数据示例(1个模拟):

[{"price":"150000","postalCode":"33000","date":"16/12/2019","type":"immobilier"}]

输入倍数数据示例(2个或更多个模拟):

[{"price":"150000","postalCode":"33000","date":"16/12/2019","type":"immobilier"}, {"price":"250000","postalCode":"75001","date":"16/12/2019","type":"area"}]

如果用户进行一次模拟,我想将第一个示例(一个对象的数组)保存在本地存储中

但是如果用户进行了几次模拟,我想保存第二个示例(多个对象的数组)

为此,您必须保存历史记录(以前的值)

  componentDidUpdate() {
    const { notary } = this.props // datas
    const { send } = this.state
    const prevResult = localStorage.getItem('notary') // check prev results 
    let arrayResult = [] // array
    if (prevResult !== null) arrayResult = JSON.parse(prevResult)
    if (notary !== null && send) {
      arrayResult.push({ date: moment().format('YYYY-MM-DD HH:mm:ss'), ...notary })
      localStorage.setItem('notary', JSON.stringify(arrayResult))
      this.setState({ send: false })
    }
  }

我试图从localstorage中检索以前的值,并将新值推入表中,但是它不起作用。

在我的案例中,很好地创建了一个由多个对象组成的数组,但是这些对象相同,而结果却不同

输出: 这就是我想在localStorage中拥有的东西

如果用户仅进行1次仿真: 一个对象的数组

[{"price":"150000","postalCode":"33000","date":"16/12/2019","type":"immobilier"}] 

如果用户进行多次模拟: 多个对象的数组

[{"price":"150000","postalCode":"33000","date":"16/12/2019","type":"immobilier"}, {"price":"250000","postalCode":"75001","date":"16/12/2019","type":"area"}]

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

在utils文件夹中创建一个localStorager.js,然后将参数发送到该localStorager函数。

  

localStorager.js

export const localStorager= state => {
   localStorage.clear();
if (state.length > 1) {
   //this condition is for multiSimulation
  state.forEach((e, i) => {
    const serializedState = JSON.stringify(e);
    localStorage.setItem(`state${i}`, serializedState);
  });
} else {
  // this else is for singleSimulation
  const serializedState = JSON.stringify(state);
  localStorage.setItem(`state`, serializedState);
}
};

然后在您的组件中想让localStorage麻烦的是,将数据传递给您之前创建的localStorager.js函数。

  

您从componentDidUpdate使用的组件

import { localStorager} from "../utils/localStorager";

...
//by the way you can use from localStorager in every function that you want.
componentDidUpdate(){
//forExsample
  let singleSimulation= [
      {
        price: "150000",
        postalCode: "33000",
        date: "16/12/2019",
        type: "immobilier"
      }
    ];
      let multiSimulation= [
      {
        price: "150000",
        postalCode: "33000",
        date: "16/12/2019",
        type: "immobilier"
      },
      { price: "250000", postalCode: "75001", date: "16/12/2019", type: "area" }
    ]
  }

 //and after that use from localStorager and pass these data to that
 localStorager(singleSimulation);
 localStorager(multiSimulation);

 //in this case you should use just pass your notary data  
 const { notary } = this.props // datas
 localStorager(notary)

  //this is end of componentDidUpdate 
  }