Node.js 中的“窗口未定义"错误

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.