网站在哪里实名认证,大兴安岭做网站,网页设计与网站开发方向,网络货运怎么做的现象#xff1a; 这个问题是直接指向了我使用的第三方库good-storage#xff0c;这是一个对localStorage/sessionStorage做了简单封装的库#xff0c;因为项目代码有一个缓存cache.ts有用到 原因分析#xff1a; 从表象上看是storage对象找不到getItem方法#xff0c;
但…现象 这个问题是直接指向了我使用的第三方库good-storage这是一个对localStorage/sessionStorage做了简单封装的库因为项目代码有一个缓存cache.ts有用到 原因分析 从表象上看是storage对象找不到getItem方法
但实际上是ssr环境中找不到windows.localStorage对象
从这里看看good-storage源码就能分析到这一点 var isServer typeof window undefined;var store {/* eslint-disable no-undef */version: 1.1.1,storage: !isServer ? window.localStorage : null,session: {storage: !isServer ? window.sessionStorage : null}};
但这个代码是有漏洞的它在csr客户端渲染环境中是没有问题的但是在ssr环境中就一定有问题。
因为有个关键点 环境中有window对象并不一定就会有window.localstorage对象 因为我为了解决document not defined问题用jsdom给ssr环境做了浏览器环境全局模拟 这意味window对象是一定存在的
所以用typeof window undefined来判断浏览器环境是不准确的
因为此时window对象明显是假的它底下不可能真正有localstorage属性
那么就必须使用window对象和window.localStorage对象同时存在的这种双重判断
才能准确判断出真实的浏览器环境 var isBrowser typeof window object ( window.localStorage ! undefined );var store {/* eslint-disable no-undef */version: 1.1.1,storage: isBrowser ? window.localStorage : undefined,session: {storage: isBrowser ? window.sessionStorage : undefined}};
同时在storage对象的get方法上也加上这个判断这样才能真正生效避免反序列化失败。 var val isBrowser ? deserialize(this.storage.getItem(key)) : undefined; 以上修改node_modules\good-storage\dist\storage.js源码然后问题解决.