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

如何比较对象并向localStorage添加/移除道具?

  •  -1
  • karolis2017  · 技术社区  · 7 年前

    一、 我有一个初始状态:

    const initialState = {
      val1: 1,
      val1: 2,
    }
    

    我想看看我的 localStorage initialState 它会时不时地改变。

    • 如果是=>跳到下一个道具
    • 如果否=>添加 prop: val 到 本地存储
    • 如果里面有道具 初始状态 =>从中移除道具 .

    在这里,我为localStorage添加了新的道具,但是在每个新的 prop

    const setNewLocalStorage = () => {
      const localStorageState = getLocalStorageState()
      let newState = localStorageState
      Object.keys(initialState).map(key => {
        if (!localStorageState.hasOwnProperty(key)) {
          newState[key] = initialState[key]
          setStateToLocalStorage(newState)
        }
        return
      })
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   joeytwiddle    7 年前

    回答XY的Y

    以下是存储数据的方法:

    const setNewLocalStorage = () => {
      Object.keys(initialState).map(key => {
        // Do various checking to decide whether or not to write
        if (!localStorageState.hasOwnProperty(key) || JSON.parse(localStorage.getItem(key)) !== initialState[key]) {
          localStorage.setItem(key, JSON.stringify(initialState[key])
        }
    
        // But actually that is more complex than need be.
        // Why not just store the data every time, and be done with?
        localStorage.setItem(key, JSON.stringify(initialState[key])
      })
    }
    

    JSON.stringify() 和 JSON.parse() 在读取或写入localStorage时,因为localStorage只存储字符串,而您的数据似乎包含数字。


    如果localStorage中存在initialState上不存在的prop=>请从localStorage中删除该prop

    因此,更安全的做法可能是有一个要删除的“旧密钥”的特定列表。或者,为您的密钥命名,这样您就知道哪些密钥属于应用程序的这一部分。

    也就是说,你可以这样做你要求的:

    for (var i = localStorage.length; i--;) {
      var key = localStorage.key(i);
      if (!initialState.hasOwnProperty(key)) {
        localStorage.removeItem(key);
      }
    }
    

        2
  •  0
  •   joeytwiddle    7 年前

    我建议您将整个state对象存储在一个键下:

    // Load state (but on first load, start with the defaultState)
    var appState = JSON.parse(localStorage.getItem('appState') || "null") || defaultState;
    
    // Save state
    localStorage.setItem('appState', JSON.stringify(appState));
    

    请注意,在第一次运行时 localStorage.appState JSON.parse() || "null" || null 进入新用户应该开始的默认状态。

    initialState 到 appState 因为这是一个更好的名字可以改变的东西。