首页 > 解决方案 > React/Javascript 比较运算符不工作

问题描述

不知何故,我无法让我的比较运算符工作。我有以下代码:

function handleNotifClickRemind(key) {
  localStorage.setItem('no_remind_change_pwd', true);
  notification.close(key);
}

// ...

<Button outline size="small" onClick={() => handleNotifClickRemind(key)}>
  Dont remind me
</Button>

// ...

console.log(localStorage.getItem('no_remind_change_pwd'));
function another_func(data) {
  if (localStorage.getItem('no_remind_change_pwd') != true) {
    openNotification('topRight');
  }
}

当我单击“不提醒我”按钮时,handleNotifClickRemind由于第三部分的日志输出打印而被触发true。然而,openNotification还是被触发了。有人可以帮忙吗?

PS我没有初始化值,我只是让它no_remind_change_pwd为空。

提前致谢。

标签: javascriptreactjs

解决方案


您在本地存储中保存的所有内容都是字符串。所以你在比较"true"!=true哪个总是true

如果要比较值,可以使用如下。 JSON.parse(localStorage.getItem('no_remind_change_pwd')) != true

这意味着,以下是true

console.log(JSON.parse("true") === true)


推荐阅读