Error `window not defined` in Node.js

那年仲夏 提交于 2019-11-29 17:37:22

问题


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

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


回答1:


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

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

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);
}

I would advise against putting state in the setTimeout.




回答2:


This will settle that issue for you:

typeof(window) === 'undefined'

Even if a variable isn't defined, you can use typeof() to check for it.




回答3:


This kind of code shouldn't even be running on the server, it should be inside some componentDidMount (see doc) hook, which is only invoke client side. This is because it doesn't make sense to scroll the window server side.

However, if you have to reference to window in a part of your code that really runs both client and server, use global instead (which represents the global scope - e.g. window on the client).




回答4:


This is a little older but for ES6 style react component classes you can use this class decorator I created as a drop in solution for defining components that should only render on the client side. I like it better than dropping window checks in everywhere.

import { clientOnly } from 'client-component';

@clientOnly
class ComponentThatAccessesWindowThatIsNotSafeForServerRendering extends Component {
    render() {
        const currentLocation = window.location;
        return (
            <div>{currentLocation}</div>
        )
    };
}

https://github.com/peterlazzarino/client-component




回答5:


<Router onUpdate={() => window.scrollTo(0, 0)} history= {browserHistory}>

if you need to open new page on top in React JS app, use this code in router.js




回答6:


Move the window and related code to the mounted() lifecycle hook. This is because mounted() hook is called on the client side only and window is available there.



来源:https://stackoverflow.com/questions/35374257/error-window-not-defined-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!