React-router无法在服务器端呈现

时间:2016-01-08 08:36:06

标签: react-router

我正在尝试使用react-router在服务器端渲染一个简单的模拟。

这是代码

import express from 'express'
import React from 'react'
import {Router} from 'react-router'
import routes from './routes'
import ReactDOMServer from 'react-dom/server'
var app = express()

app.use((req, res)=> {
    res.send('<!DOCTYPE html>' + ReactDOMServer.renderToString(<Router routes={routes}/>))
})

app.listen('8080', function () {
  console.log('Server started at port 8080')
})

并收到以下错误

Invariant Violation: Hash history needs a DOM

我正在使用最新版本的react-router。我让它使用旧版本

 import express from 'express'
import React from 'react'
import {Router} from 'react-router'
import routes from './routes'
import ReactDOMServer from 'react-dom/server'
var app = express()

app.use((req, res)=> {
  Router.run(routes, req.path, (Handler) => {
    res.send('<!DOCTYPE html>' + ReactDOMServer.renderToString(<Router routes={routes}/>))
  })
})

app.listen('8080', function () {
  console.log('Server started at port 8080')
})

1 个答案:

答案 0 :(得分:3)

您需要使用match()函数和<RoutingContext>(2.x RC中的<RouterContext>)在服务器上呈现。请按照服务器呈现指南进行操作:https://github.com/rackt/react-router/blob/v1.0.3/docs/guides/advanced/ServerRendering.md