我在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')
)
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
的{{1}}组件来获取路由链接。这就是我渲染它们的方式:
<Link />
答案 0 :(得分:0)
这是因为您将html属性添加到<Link/>
组件
example:
<Link to="/listeners" className="appFooter-nav-link">Life Guides</Link>
^ you are not supposed to add className
<Link/>
react-router-dom的组成部分除to
,replace
,innerRef
和component
之外,不应有其他道具,否则会产生意外结果
有关Link组件,请参见react-router-dom参考