我正在尝试使用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')
})
并出现以下错误
不变违规:哈希历史记录需要 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')
})
最佳答案
您需要使用match()
功能和<RoutingContext>
(<RouterContext>
在 2.x RC 中)在服务器上渲染。请遵循服务器渲染指南:https://github.com/rackt/react-router/blob/v1.0.3/docs/guides/advanced/ServerRendering.md .
关于React-router 无法在服务器端渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34672644/