Node.js 中的“窗口未定义"错误 [英] Error `window not defined` in Node.js

查看:62
本文介绍了Node.js 中的“窗口未定义"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 window 在 Node.js 中不存在,但我在客户端和服务器上使用 React 和相同的代码.我用来检查 window 是否存在的任何方法都会让我感到:

I know window doesn't exist in Node.js, but I'm using React and the same code on both client and server. Any method I use to check if window exists nets me:

未捕获的引用错误:窗口未定义

Uncaught ReferenceError: window is not defined

如何解决我无法执行 window && 的事实window.scroll(0, 0)?

How do I get around the fact that I can't do window && window.scroll(0, 0)?

推荐答案

Sawtaytoes 已经搞定了.我会运行你在 componentDidMount() 中的任何代码并用:

Sawtaytoes has got it. I would run whatever code you have in componentDidMount() and surround it with:

if (typeof(window) !== 'undefined') {
  // code here
}

如果在 React 渲染组件时窗口对象仍未被创建,你总是可以在组件渲染后的几分之一秒内运行你的代码(并且窗口对象到那时肯定已经创建了)所以用户看不出区别.

If the window object is still not being created by the time React renders the component, you can always run your code a fraction of a second after the component renders (and the window object has definitely been created by then) so the user can't tell the difference.

if (typeof(window) !== 'undefined') {
    var timer = setTimeout(function() {
        // code here
    }, 200);
}

我建议不要在 setTimeout 中放置状态.

I would advise against putting state in the setTimeout.

这篇关于Node.js 中的“窗口未定义"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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