反转存储在localStorage中的布尔值 [英] Reversing a Boolean stored in localStorage

查看:80
本文介绍了反转存储在localStorage中的布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以切换黑暗模式的按钮.我将暗模式状态作为Boolean存储在localStorage中.

I have a button that toggles dark mode. I store the dark mode state as Boolean in localStorage.

按钮调用此函数,该函数应翻转布尔值,但它不起作用.

The button invokes this function that should flip the Boolean, but it isn't working.

const handleDarkMode = () => {
  let darkMode = localStorage.darkMode
  localStorage.setItem("darkMode", !darkMode)
}

有什么想法吗?

推荐答案

本地存储中的项目以字符串形式存储,因此您需要将"true" /"false" 值转换为 true / false (布尔)值,然后才能使用 darkMode 作为布尔值:

Items in local storage are stored as strings, thus you need to turn your "true"/"false" values into true/false (boolean) values before you can use darkMode as a boolean:

const handleDarkMode = () => {
  let darkMode = localStorage.darkMode === "true"; // change "true" to true and others to false
  localStorage.setItem("darkMode", !darkMode)
}

还请注意:通常,要从localStorage获取项目,我们使用 getItem(key)

Also note: In general to get an item from localStorage we use getItem(key)

这篇关于反转存储在localStorage中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆