如何在服务器端将变量从 react-router 传递给子组件。 我想将一些变量传递给由 RoutingContext 呈现的组件
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from './routes'
serve((req, res) => {
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(<RouterContext {...renderProps} />))
} else {
res.status(404).send('Not found')
}
})
})
最佳答案
尝试将自定义 Prop 添加到渲染 Prop 时遇到同样的问题。
我发现这个链接非常有用:
https://github.com/reactjs/react-router/issues/2073
注:见最后一条评论
如果我理解您在评论中的意思——您需要一种将服务器数据传递到客户端组件的方法。
我倾向于使用 EJS(或您在 express 中使用的任何模板语言)将其呈现出来,以将 JSON 字符串分配给 HTML 中的脚本标记并将其分配给窗口范围。
所以你的 index.ejs 文件看起来会包含类似的东西
<body>
<main>
<%- markup %>
</main>
<script>
window.data = JSON.parse('<%- data %>');
</script>
</body>
然后在你的服务器js
var customProps = {}; // the data you are passing in
var markup = renderToString(...); // your renderToString stuff you did before
var data = {
markup: markup,
data: JSON.stringify(customProps)
};
res.status(200).render(index.ejs', data);
然后在你的顶级路由中你可以引用window.data
*
- 注意:您需要添加一些条件才能知道您使用的是浏览器还是服务器,我使用 https://www.npmjs.com/package/is-browser
关于javascript - 将变量从 react-router 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419846/