Error `window not defined` in Node.js

爷,独闯天下 提交于 2019-11-30 11:29:52

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.

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.

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).

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

<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

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.

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