问题描述
我的版本为1.0.0-rc1,而我的match函数无法正确显示我的路线.
I'm with version 1.0.0-rc1 and my match function won't render my route correctly.
这是我的服务器
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>
.就这么简单.
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.
我基于此 https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ServerRendering.md
谢谢
推荐答案
您正在使用子路由.这意味着,当您转到"/home"时,首先呈现应用程序,然后将子Home插入并通过Application组件内部的this.props.children
进行访问.有关简单示例,请参见此处:
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:
尝试一下(不嵌套):
<Route path="/" component={Application}>
<Route path="/home" component={Home} />
如果要在Home组件周围渲染Application组件,请使用
If you want to render your Application component around the Home component use
render() {
return (
<div>
<h1>Application</h1>
{ this.props.children }
</div>
);
}
这篇关于服务器端react-router不会渲染我的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!