React/Javascript比较运算符不生效问题排查求助
问题根因
LocalStorage仅支持存储字符串类型的值,你调用setItem存入布尔值true时,会被自动转换为字符串"true",后续取值时拿到的也是字符串类型,直接和布尔值true做比较就会出现类型不匹配的问题。
你打印时看到的true实际是字符串内容,和布尔值类型不同,你可以追加打印typeof localStorage.getItem('no_remind_change_pwd'),会看到输出为string而非boolean。你现有代码中的判断localStorage.getItem('no_remind_change_pwd') != true实际执行逻辑是:
- 点击按钮后取值为字符串
"true",和布尔true做非严格不等比较,"true" != true的结果为true,所以会进入if分支执行openNotification - 未初始化时取值为
null,null != true结果也为true,符合你默认要弹出通知的需求
修复方案
- 方案1:直接和字符串
"true"做比较,改动最小
if (localStorage.getItem('no_remind_change_pwd') !== "true") { openNotification('topRight'); }
- 方案2:把取值结果显式转成布尔值再比较,逻辑更清晰,也适配未初始化的null场景
const noRemind = localStorage.getItem('no_remind_change_pwd') === 'true' if (!noRemind) { openNotification('topRight'); }
- 方案3:如果后续要存更多非字符串类型到localStorage,可以统一做序列化/反序列化处理
存值时:
localStorage.setItem('no_remind_change_pwd', JSON.stringify(true));
取值时:
const noRemind = JSON.parse(localStorage.getItem('no_remind_change_pwd') ?? 'false') if (!noRemind) { openNotification('topRight'); }
内容的提问来源于stack exchange,提问作者crimsonpython24
相关产品推荐
相关产品推荐

