如何避免在 ReactJS 同构应用程序中的服务器上出现错误“localStorage 未定义"? [英] How to avoid getting error 'localStorage is not defined' on server in ReactJS isomorphic app?

查看:35
本文介绍了如何避免在 ReactJS 同构应用程序中的服务器上出现错误“localStorage 未定义"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 webApp 中使用 localStorage 在客户端存储数据.但是当我试图使应用程序同构时,这会导致一个问题.由于 node 不是浏览器环境,它不能定义诸如 'window'、'localStorage' 等对象.我该如何解决这个问题?

I was using localStorage in my webApp to store data on client side. But when I've tried to make the app isomorphic, this causes an issue. Due to node is not browser environment, it can't define such objects as 'window', 'localStorage' etc. How do I solve this issue?

推荐答案

您可以通过检查模块是否不是 'undefined' 来检查代码是在服务器上执行还是在客户端执行代码>:

You could use a check whether the code is being executed on the server or on the client side by checking whether module is not 'undefined':

var isNode = typeof module !== 'undefined'

然后您可以继续只在客户端执行此代码:

You can then proceed to only executed this code on the client side:

if(!isNode){
   //use the local storage
   var myItem = localStorage.getItem(itemTitle)
}

但是,您应该在使用前检查是否定义了Storage,因为并非所有浏览器都支持它:

However, you should already always check whether Storage is defined before using since not all browsers support it:

if(typeof(Storage) !== "undefined"){
   //use the local storage
}

这篇关于如何避免在 ReactJS 同构应用程序中的服务器上出现错误“localStorage 未定义"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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