简体   繁体   中英

react-router-dom on the server

I did find out that I can't use when I'm rendering my app on the server. I would like to wrap my App in specified router depending on the situation - BrowserRouter on the CLient side and StaticRouter on server side. My App looks like this:

imports......
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }

  render() {
      return (
        <BrowserRouter>
          <div>
            <Menu />
            <main>
              <Switch>
                <Route exact path="/about" component = {About} />
                <Route exact path="/admin" component = {BooksForm} />
                <Route exact path="/cart" component = {Cart} />
                <Route exact path="/" component = {BookList} />
              </Switch>
              <Footer />
            </main>
          </div>
        </BrowserRouter>
      );

  }

  componentDidMount(){
    this.props.getCart();
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    getCart
  }, dispatch)
}

export default connect(null, mapDispatchToProps)(App);

I tried to move my BrowserRouter ou of this component so my index.js would look like this:

imports....
const renderApp = () => (
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <App/>
    </BrowserRouter>
  </Provider>
)

const root = document.getElementById('app')
render(renderApp(), root)

So I would get ability to wrap my app in different routers. The problem is when I moved BrowserRouter out of my App component it stopped working. Clicking on links just does not work anymore. The url is changing but my app isn't rendering differnet components. How can I move router out of this component?

On the server, you'll wrap your app similar to this:

 const routerContext = {};

 const appComponent = (
    <Provider store={store}>
      <StaticRouter location={req.url} context={routerContext}>
        <App />
       </StaticRouter>
    </Provider>
  );

Where you pass react-router the location (from the url) as well as a context object.

The client side is like your example:

<Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <App/>
  </BrowserRouter>
</Provider>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM