将变量从 react-router 传递给子组件

Passing variable from react-router to child components

如何在服务器端将变量从 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')
    }
  })
})

尝试将自定义道具添加到渲染道具时遇到同样的问题。

我发现这个 link 非常有用:

https://github.com/reactjs/react-router/issues/2073

注:见最后一条评论


如果我理解您在评论中的意思 - 您需要一种将服务器数据传递到客户端组件的方法。

我倾向于使用 EJS(或您在 express 中使用的任何模板语言)将其呈现出来,以将 JSON 字符串分配到 HTML 中的脚本标记并将其分配给 window范围。

因此您的 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*