简体   繁体   中英

Server side react-router won't render my routes

I'm with version 1.0.0-rc1 and my match function won't render my route correctly.

This is my server

import express from 'express';
import React from 'react';
import createLocation from 'history/lib/createLocation'
import Router, { match, RoutingContext } from 'react-router';
import createRoutes from './create-routes';

const app = express();
const routes = createRoutes();

app.use((req, res) => {
  let location = createLocation(req.url);

  match({ routes, location }, (error, redirectLocation, renderProps) => {
    if (redirectLocation)
      res.status(301).redirect(redirectLocation.pathname + redirectLocation.search)
    else if (error)
      res.status(500).send(error.message)
    else if (renderProps == null)
      res.status(404).send('Not found')
    else
      res.send(React.renderToString(<RoutingContext {...renderProps}/>))
  });
});

export default app;

This is my routes

import React from 'react';
import { Route } from 'react-router';
import Application from './components/Application.react';
import Home from './components/Home.react';

export default function() {
  return (
    <Route path="/" component={Application}>
      <Route path="home" component={Home} />
    </Route>
  );
}

What do i do wrong in this? When i ask for /home, it should render <h1>Home</h1> instead of <h1>Application</h1> . Just simple as that.

I based this on this https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ServerRendering.md

Thank you

You are using subroutes. This means, that when you go to "/home" first Application is rendered, then the child Home is injected and available via this.props.children inside of the Application Component. See here for a simple example:

Try this (not nested):

<Route path="/" component={Application}>
<Route path="/home" component={Home} />

If you want to render your Application component around the Home component use

render() {
    return (
        <div>
            <h1>Application</h1>
            { this.props.children }
        </div>
    );
}

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