【问题标题】:Server side react-router won't render my routes服务器端 react-router 不会渲染我的路由
【发布时间】:2015-12-23 17:17:27
【问题描述】:

我使用的是 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 时,它​​应该呈现 &lt;h1&gt;Home&lt;/h1&gt; 而不是 &lt;h1&gt;Application&lt;/h1&gt;。就这么简单。

我基于这个https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ServerRendering.md

谢谢

【问题讨论】:

    标签: node.js express reactjs react-router


    【解决方案1】:

    您正在使用子路由。这意味着,当您转到“/home”时,首先呈现应用程序,然后子 Home 被注入并通过应用程序组件内部的this.props.children 可用。 一个简单的例子见here

    试试这个(不是嵌套的):

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

    如果您想在 Home 组件周围呈现您的应用程序组件,请使用

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

    【讨论】:

    • 在 :) 中编辑了 Application 组件的渲染
    • 查看问题,你将如何渲染 childRoutes 然后服务器端?
    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2016-03-26
    • 2016-11-17
    • 1970-01-01
    • 2020-12-11
    • 2016-05-29
    相关资源
    最近更新 更多