服务器端的React-Router不会渲染我的路由

4
我是版本1.0.0-rc1,我的匹配功能无法正确渲染我的路由。
这是我的服务器。
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;

这是我的路由

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>
  );
}

我在这里做错了什么?当我请求 /home 时,它应该呈现 <h1>Home</h1> 而不是 <h1>Application</h1>。就是这么简单。
我基于 https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ServerRendering.md 进行了此操作。
谢谢。
1个回答

1
您正在使用子路由。这意味着,当您首先访问 "/home" 时,将呈现第一个应用程序,然后注入并通过应用程序组件内的 this.props.children 可用的子 Home 组件。 请参见 此处 的简单示例:
尝试这个(非嵌套):
<Route path="/" component={Application}>
<Route path="/home" component={Home} />

如果您想在主页 (Home) 组件周围呈现应用程序 (Application) 组件,请使用:
render() {
    return (
        <div>
            <h1>Application</h1>
            { this.props.children }
        </div>
    );
}

已编辑了应用程序组件的渲染 :) - Herku
看到这个问题了,那么在服务器端如何渲染 childRoutes 呢? - Mo Binni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接