In React, how do I detect if my component is rende

2020-02-26 03:00发布

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 when I'm rendering in the client.

How do I detect if I'm at the client or at the server? I'm looking for something like isClient() or isServer().

8条回答
啃猪蹄的小仙女
2楼-- · 2020-02-26 03:49

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
);
查看更多
太酷不给撩
3楼-- · 2020-02-26 03:50

Two things that may be relevant:

Many projects use some convention where they set a global SERVER or CLIENT boolean so all your code can switch based off it. In your server bundle, set some global, like in this project

global.__SERVER__ = true;

And in your client bundle, set some global client to true, which you can achieve one way with Webpack's DefinePlugin

new webpack.DefinePlugin({
  __CLIENT__: true
})

With the above approach, you could switch based off that variable in willMount, or render, to do one thing on the server, and another on the client.

The second thing that may be helpful here is componentDidMount only runs on the client, but not on the server.

查看更多
登录 后发表回答