react 服务器端渲染 ssr 中 localstorage/history/window is not defined 解决方案

本文探讨了服务器端渲染(SSR)过程中遇到的问题,即在服务器环境中尝试访问浏览器特有属性(如window和localStorage)时引发的错误,并提供了一种解决方案:通过使用ES6的Proxy来代理这些浏览器属性,确保在SSR环境下也能正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1、原因

  

  ssr 会在后端执行组件的 componentWillMount 以及在它这个生命周期之前的生命周期

    也就是说 ssr 阶段是不会执行 componentDidMount 方法的

 

 当你在 componentWillMount 之前当生命周期里面调用 window / localstorage 全局对象的时候,

 它其实是在服务器上面执行等,因为 window / localstorage 是浏览器的属性对象。

 所以在 服务器端 跑的时候,就会出现没有定义的错误。

 

2、解决方案

  

  个人觉得可以把这些浏览器的属性重新封装以便使用。

  例如:

   let targetWin = null
    if(window) targetWin = window
    var proxyWindow = new Proxy(targetWin,{
        get: function (target, key, receiver) {
            if(!targetWin) {
                return Reflect.get({nothing:function () {}}, 'nothing', receiver);
            }
            return Reflect.get(target, key, receiver);
        }
    });

    export default proxyWindow

  

  没有在项目中试过,不过我觉得这是一个完美解决方案。

  上面是用了 es6 的 proxy 做代理。

  当 window 不存在时候,如果调用了 window 上面的方法或者属性就会执行 nothing 这个方法。

  也就是说 在服务器渲染的时候 不会找不到 window ,而会执行 nothing 方法。

  这样就不会报错了。

  这里的话,以后使用 window 的对象的话,就需要引用这个模块。

 

  以此类推,localstorage / location 等都可以用此类方法实现了。

 

Error occurred prerendering page “/_not-found”. Read more: https://nextjs.org/docs/messages/prerender-error ReferenceError: localStorage is not defined at f (C:\boiler\boiler\boiler-ui.next\server\app_not-found\page.js:1:5101) at nO (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:45959) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:47734) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:62515) at nL (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:65533) at nN (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:63164) at nB (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:68946) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:59382) at nL (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:65533) at nN (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:63164) Export encountered an error on /_not-found/page: /_not-found, exiting the build. ⨯ Next.js build worker exited with code: 1 and signal: null打包报错这个信息,我的localStorage卸载components包下的文件中,下面是内容const handleLogout = () => { localStorage.removeItem('token'); // setIsLoggedIn(false); localStorage.setItem("loginStatus", "false") router.push("login") }请告诉我怎么改
03-27
Error occurred prerendering page "/pass". Read more: https://nextjs.org/docs/messages/prerender-error ReferenceError: localStorage is not defined at v (C:\boiler\boiler\boiler-ui\.next\server\app\pass\page.js:1:11490) at nO (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:45959) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:47734) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:62515) at nL (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:65533) at nN (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:63164) at nB (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:68946) at nI (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:59382) at nL (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:65533) at nN (C:\boiler\boiler\boiler-ui\node_modules\next\dist\compiled\next-server\app-page.runtime.prod.js:20:63164) Export encountered an error on /pass/page: /pass, exiting the build. ⨯ Next.js build worker exited with code: 1 and signal: null打包时报错以上信息,localStorage已经定义如下const handleLogout = () => { if (typeof window !== 'undefined') { localStorage.removeItem('token'); localStorage.setItem("loginStatus", "false"); router.push("login"); } },下面代码我该如何修改export async function axiosPost(url: any, data: any = null, ContentType: string = 'application/json') { return axios("http://10.143.22.25:8080" + url, { method: 'post', headers: { 'Content-Type': ContentType, 'token': localStorage.getItem('token') }, data: data }) }
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值