在本地存储中设置多个变量的最佳方法

Best way to set multiple variables in local storage

我正在制作一个用于向我的网站添加食谱的表单,我想将每个表单输入的内容存储在本地存储中,这样它们就不会在页面刷新时丢失。我的表单上有大约 10 个输入,它们的内容都处于反应状态。是将每个变量保存在一个对象中并将其存储为一个本地存储项以在每次变量状态更改时更改,还是将每个变量保存在单独的本地存储项中更好。

选项 1:

const [a, setA] = useState('')
const [b, setB] = useState('')
// Many more variables...

useEffect(() => {
  const recipes = JSON.parse(localStorage.getItem('recipes'))
  if (recipes) {
    setA(recipes.a)
    setB(recipes.b)
    // For each variable...
  }
}, [])

// Update 'recipe' item in local storage on any form input state change
useEffect(() => {
  localStorage.setItem('recipe', JSON.stringify({a, b}))
}, [a, b])

选项 2:

// Set each state to it's local storage item or an empty string if local storage is empty
const localA = localStorage.getItem('a')
const [a, setA] = useState(JSON.parse(() => (localA ? localA : '')))
const localB = localStorage.getItem('b')
const [b, setB] = useState(JSON.parse(() => (localB ? localB : '')))

// Set each individual local storage item on state change
useEffect(() => {
  localStorage.setItem('a', JSON.stringify(a))
}, [a])

useEffect(() => {
  localStorage.setItem('b', JSON.stringify(b))
}, [b])

我只想知道对于大量变量最好的方法是什么,或者是否还有更好的方法来解决这个问题。非常感谢!

如果您将表单状态保持为对象形式,则必须将其序列化以将其放入本地存储,因此序列化和反序列化该对象会产生一些成本。独立存储每个字段的值的替代方案不会有这种反序列化开销。我不认为序列化的开销是一个简单形式的问题,所以我会采用对象方法。

也许中间方法是使用表单对象方法,但仅在 window 为 closed or unloaded 时才坚持使用它。

window.onclose = () => {
    // Save the form state to local storage.
}

您可以使用多个变量,

如果您想尽量减少序列化,只需使用此帮助文件即可重用功能并使您的代码整洁。

辅助文件:https://gist.github.com/scrubmx/a240a912a475ab0a2c43

If you are going to build a larger app with redux state management, I will strongly recommend you to use redux-persist. You no need to worry about serializing and deserializing. There are a lot of features you can use.

文档:https://www.npmjs.com/package/redux-persist