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

标签 javascript node.js reactjs react-router

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

关于javascript - 将变量从 react-router 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419846/

相关文章:

node.js - 如何对 express-http-proxy 进行单元测试

javascript - 如何在 node.js 上连接 reactJS 和 mysql

javascript - 如何使用 ES6 API 重复一系列 Promise

javascript - promise : How to execute async methods in parallel then execute method

javascript - node-webkit 右键单击​​链接并在默认浏览器中打开

javascript - Mongoose - 检索到的文档中没有 '_id' 属性

javascript - 超出最大调用堆栈大小 - Connected React Component

python - 使用 FilePond(React 组件)将图像上传到 Flask 服务器

javascript 在 w3schools.com 上运行,但不在 jsfiddle.net 上运行?

javascript - 我可以在对象类的更改上触发或执行 JavaScript 函数吗?