使用react-router进行SSR:客户端为每条路由

时间:2017-04-18 15:59:40

标签: javascript reactjs meteor react-router serverside-rendering

我在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 />
          

这是如何渲染的:
enter image description here

1 个答案:

答案 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的组成部分除toreplaceinnerRefcomponent之外,不应有其他道具,否则会产生意外结果

有关Link组件,请参见react-router-dom参考

https://reactrouter.com/web/api/NavLink