迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

Javascript 错误 ReferenceError: localStorage is not defined Error

作者:迹忆客 最近更新:2022/10/14 浏览次数:

出现“ReferenceError: localStorage is not defined”错误有多种原因:

  1. 在 Node.js 中使用 localStorage。
  2. 在服务器上使用 localStorage(例如 Next.js 中的服务器端渲染)。
  3. 拼写错误的 localStorage 全局变量(应该是小驼峰式)。

javascript ReferenceError localStorage is not defined

localStorage 属性是 window 对象的属性,因此它在服务器上不可用。

console.log(localStorage === window.localStorage); // 👉️ true

localStorage.setItem('name', 'jiyik');

console.log(localStorage.getItem('name')); // 👉️ "jiyik"

如果我们在浏览器中遇到错误,请确保没有拼错 localStorage 关键字(应该是小驼峰式)。

如果你使用的是 React.jsNext.js,并且需要检查我们是在浏览器上(可以使用 localStorage)还是在服务器上(不能使用 localStorage),可以通过以下方式执行此操作:

if (typeof window !== 'undefined') {
  console.log('浏览器端')
  // 👉️ 可以使用 localStorage 
} else {
  console.log('服务器端r')
  // 👉️ 不可以使用 localStorage
}

我们检查全局 window 变量是否没有 undefined 的类型。 如果定义了全局 window ,我们就在浏览器端,可以使用 localStorage 对象。

要解决“ReferenceError: localStorage is not defined”错误,需要确保仅在浏览器中使用 localStorage 对象。 localStorage 属性在 window 对象上定义,在服务器上不可用 - 例如 在 Node.js 中或在 Next.js 中使用服务器端渲染时。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便