In React, how do I detect if my component is rendering from the client or the server?

前端 未结 9 1152
夕颜
夕颜 2020-12-29 18:41

I\'m building a isomorphic application, but I\'m using a third-party component that only renders on the client. So, particularly for this component, I need to only render it

相关标签:
9条回答
  • 2020-12-29 19:41

    You can check if global window variable is defined or not. as in browser it should always be defined.

    var isBrowser = window!==undefined
    
    0 讨论(0)
  • 2020-12-29 19:41

    At the topmost level of the server Element hierarchy, one could add a ServerContext such as this:

    class ServerContext extends React.Component {
      getChildContext() { return { isServer: true }; }
      render() { return React.Children.only(this.props.children); }
    }
    
    ServerContext.propTypes = {
      children: React.PropTypes.node.isRequired,
    };
    
    ServerContext.childContextTypes = {
      isServer: React.PropTypes.bool.isRequired,
    };
    
    // Create our React application element.
    const reactAppElement = (
      <ServerContext>
        <CodeSplitProvider context={codeSplitContext}>
          <ServerRouter location={request.url} context={reactRouterContext}>
            <DemoApp />
          </ServerRouter>
        </CodeSplitProvider>
      </ServerContext>
    );
    

    Doing so, it should be possible to read the isServer from the context like this:

    const Layout = (_, { isServer }) => (
      // render stuff here
    );
    
    0 讨论(0)
  • 2020-12-29 19:42

    You can also use componentDidMount(), as this lifecycle method is not run when the page is server-side rendered.

    0 讨论(0)
提交回复
热议问题