我是React的新手,并遵循构建同构应用程序的教程。在服务器端,它使用router.run()
执行渲染操作,但它在react-router 1.0.0中被删除。
Router.run(routes, req.url, Handler => {
let content = React.renderToString(<Handler />);
res.render('index', {
content: content
});
});
更新指南所说的是
// v0.13.x
Router.run(routes, (Handler) => {
render(<Handler/>, el);
})
// v1.0
render(<Router>{routes}</Router>, el)
但是如何处理服务器渲染呢?
答案 0 :(得分:1)
示例:
import { renderToString } from 'react-dom/server'
import { match, RoutingContext } from 'react-router'
import routes from './routes'
serve((req, res) => {
// Note that req.url here should be the full URL path from
// the original request, including the query string.
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
res.status(200).send(renderToString(<RoutingContext {...renderProps} />))
} else {
res.status(404).send('Not found')
}
})
})
可以找到更多in the docs。