代码之家  ›  专栏  ›  技术社区  ›  soccerway

但是,我们如何避免创建多个函数来保存到localStorage中呢?

  •  0
  • soccerway  · 技术社区  · 3 年前

    我们如何保存和保留localStorage对象,而不是创建多个函数?第一个localStorage对象将替换为新的存储。为了避免这种情况,我创建了一个名为 saveLocalStorageDataTwo 这是有效的。但是,我们如何避免创建多个函数来将数据保存到localStorage中呢?有办法吗?请给我一些建议好吗?

    /*localStorage.js*/

    let localStorageData = {};
    let localStorageDataTwo = {};
    
    function saveLocalStorageData ({autoId, quoteId, taskId }) {
        localStorageData = {
            autoId: autoId,
            quoteId: quoteId,
            taskId: taskId,
        }
        return localStorageData
    }
    
    function saveLocalStorageDataTwo ({data}){
        localStorageDataTwo = {
            data : data,
        }
        return localStorageDataTwo
    }
    
    export { saveLocalStorageData, saveLocalStorageDataTwo };
    

    //保存到本地存储:

    let localData = require("../../support/localStorage");
    
    const data = "Some Data 260-255"
    const localStorageData = localData.saveLocalStorageData({ autoId });
    window.localStorage.setItem('localStorageData ', JSON.stringify(localStorageData ));
    

    enter image description here

    0 回复  |  直到 3 年前
        1
  •  1
  •   Roko C. Buljan    3 年前
    • 你根本不使用任何严格的参数,比如 {autoId, quoteId, taskId} 只要通过任意 data .
    • 不要叫什么 saveLocalStorageData 如果那是真的 这个函数的作用。

    相反

    const LS = {
      set(key, data) { localStorage[key] = JSON.stringify(data); },
      get(key) { return JSON.parse(localStorage[key]); },
    };
    // export { LS };
    
    // import { LS } from "./localstorage.js"
    
    // Example saving multiple data in different LS keys
    LS.set("one", {autoId: 1, quoteId: 2, taskId: 3});
    LS.set("two", {autoId: 7});
    
    
    // Example saving Object, and later update one property value
    const data = {a: 1, b: 2, c: 3};
    LS.set("single", data); // Save
    LS.set("single", {...LS.get("single"), c: 99999}); // Update
    console.log(LS.get("single")); // {a:1, b:2, c:99999}
    
    
    // Example saving multiple data into a single Array:
    LS.set("arr", []); // Save wrapper Array
    LS.set("arr", LS.get("arr").concat({a: 1, b: 2}));
    LS.set("arr", LS.get("arr").concat({e: 7, f: 9}));
    console.log(LS.get("arr")); // [{"a":1,"b":2}, {"e":7,"f":9}]
    

    jsFiddle playground

    或者在上一个例子中,您可以使用Object而不是Array。这完全取决于需求。