react-router 4 - Browser history needs a DOM

前端 未结 3 894
清酒与你
清酒与你 2020-12-05 06:47

I am trying server side rendering using react-router 4. I am following the example provided here https://reacttraining.com/react-router/web/guides/server-rendering/putting-i

相关标签:
3条回答
  • 2020-12-05 07:24

    In clientIndex.js

    Rather than BrowserRouter use StaticRouter.

    import { BrowserRouter } from 'react-router-dom';

    import { StaticRouter } from 'react-router-dom'

    0 讨论(0)
  • 2020-12-05 07:35

    As is essentially noted in the comments, one may hit this error (as I have) by accidentally wrapping your App component in a <BrowserRouter>, when instead it is your client app that should be wrapped.

    App.js

    import React from 'react'
    
    const App = () => <h1>Hello, World.</h1>
    
    export default App
    

    ClientApp.js

    import React from 'react'
    import { BrowserRouter } from 'react-router-dom'
    import ReactDOM from 'react-dom'
    import App from './App'
    
    const render = Component => {
      ReactDOM.render(
        <BrowserRouter>
          <Component />
        </BrowserRouter>,
        document.getElementById('app')
      )
    }
    
    render(App)
    

    See also the React Router docs.

    0 讨论(0)
  • 2020-12-05 07:38

    You need to use different history provider for server side rendering because you don't have a real DOM (and browser's history) on server. So replacing BrowserRouter with Router and an alternate history provider in your app.js can resolve the issue. Also you don't have to use two wrappers. You are using BrowserRouter twice, in app.js as well as clientIndex.js which is unnecessary.

    import { Route, Router } from 'react-router-dom';
    import { createMemoryHistory } from 'history';
    
    const history = createMemoryHistory();
    
      <Router history={history}>
       <Route path="/" exact render={( props ) => ( <div>Helloworld</div> )} />
      </Router>
    

    You can now replace StaticRouter with ConnectedRouter which can be used both in client and server. I use the following code to choose between history and export it to be used in ConnectedRouter's history.

    export default (url = '/') => {
    // Create a history depending on the environment
      const history = isServer
        ? createMemoryHistory({
            initialEntries: [url]
         })
       : createBrowserHistory();
    }
    
    0 讨论(0)
提交回复
热议问题