Here's an example from the docs.
import { renderToString } from 'react-dom/server'
import { match, RouterContext } 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) {
// You can also check renderProps.components or renderProps.routes for
// your "not found" component or route respectively, and send a 404 as
// below, if you're using a catch-all route.
res.status(200).send(renderToString(<RouterContext {...renderProps} />))
} else {
res.status(404).send('Not found')
}
})
})
我有一个像这样的对象:
let reactServerProps = {
'gaKey': process.env.GA_KEY,
'query': req.query,
}
我正在尝试在这里将此对象传递给React Router。
res.status(200).send(renderToString(<RouterContext {...renderProps} {...reactServerProps} />))
我似乎无法从组件内部提供对变量的访问。
props
命名空间将所有组件连接起来,寻找变量。有没有办法将数据作为props
传递? - ThomasReggiassign()
方法直接将你的数据注入到renderProps
中。例如)assign(renderProps.params, reactServerProps)
。 - Brad Colthurst