【发布时间】:2017-09-14 13:49:51
【问题描述】:
我在一个 Meteor + React 项目中工作,该项目需要使用 react-router 进行服务器端渲染 (SSR)。当前的react-router 版本是v3,我遵循了关于SSR 的教程here。总结的步骤是:
- 创建通用路由文件
- 在客户端路由器中包含路由文件
// index.js
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
// import routes and pass them into <Router/>
import routes from './modules/routes'
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
)
- 在服务端:匹配路由到url,为每个路由渲染正确的组件
import { WebApp } from 'meteor/webapp';
import express from 'express';
const app = express();
app.get('*', (req, res) => {
// match the routes to the url
match({ routes: routes, location: req.url }, (err, redirect, props) => {
// `RouterContext` is what the `Router` renders. `Router` keeps these
// `props` in its state as it listens to `browserHistory`. But on the
// server our app is stateless, so we need to use `match` to
// get these props before rendering.
const appHtml = renderToString(<RouterContext {...props}/>)
// dump the HTML into a template, lots of ways to do this, but none are
// really influenced by React Router, so we're just using a little
// function, `renderPage`
res.send(renderPage(appHtml))
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<link rel=stylesheet href=/index.css>
<div id=app>${appHtml}</div>
<script src="/bundle.js"></script>
`
}
WebApp.connectHandlers.use(app);
这里的问题是每次我导航到客户端的新路由时,它都会向服务器发送一个新请求以获取呈现的页面。在教程应用程序中,只有一个初始请求发送到服务器,从那时起客户端将接管并处理路由(这是正确/预期的行为)。
PS:我使用react-router 的<Link /> 组件链接到路由。这就是我渲染它们的方式:
<div className="row">
<div className="eight columns offset-by-two">
<nav className="appFooter-nav">
<Link to="/listeners" className="appFooter-nav-link">Life Guides</Link>
<Link to="/mission" className="appFooter-nav-link">Mission</Link>
<Link to="/contact" className="appFooter-nav-link">Contact</Link>
<Link to="/legals" className="appFooter-nav-link">Legals</Link>
</nav>
</div>
</div>
【问题讨论】:
-
您能否说明如何在遇到问题的组件中呈现您的
a。 -
感谢@Panther,我更新了我的帖子,说明了我如何呈现我的链接。
-
想不通。在浏览器中呈现代码后,您的
react-router似乎没有启动。a标签在呈现的 html 中看起来如何? -
@Panther 我用呈现的 HTML 的外观更新了我的帖子。
-
嘿,你在这方面进化了吗? @sonlexqt
标签: javascript reactjs meteor react-router server-side-rendering