将props传递给服务器中React路由器的处理程序

时间:2015-08-25 16:01:42

标签: javascript node.js typescript reactjs react-router

我正在关注react-router指南

中报告的示例
var App = React.createClass({
  render: function () {
    return <div>Hi</div>;
  }
});

var routes = (
  <Route handler={App} path="/" />
);

// if using express it might look like this
app.use(function (req, res) {
  // pass in `req.url` and the router will immediately match
  Router.run(routes, req.url, function (Handler) {
    var content = React.renderToString(<Handler/>);
    res.render('main', {content: content});
  });
});
很简单,不是吗?相反,这是我的代码:

export function index(req: express.Request, res: express.Response, next: Function) {
    Router.run(routes, req.url, (Handler, state) => {
        fs.readFileAsync(
            path.join(__dirname, '..', 'mockData/airport-codes.csv'),
            'utf-8'
        ).then((content) => {
            return csv.parseAsync(content);
        }).then((parsedContent: Array<string[]>[]) => {
            ResponseHelper.renderTemplate('index', res, {
                output: React.renderToString(React.createElement(Handler, {
                    header: [
                        "ID", "Type", "Name", "Latitude (deg)", "Longitude (deg)", "Elevation", "Continent", "Country ISO", "Region ISO", "Municipality", "GPS Code", "IATA Code", "Local Code"
                    ],
                    initialData: parsedContent
                }))
            });
        }).catch(next);
    });
}

基本上我所做的是获取数据并传递给Handler来初始化组件。这是react中的文件路由:

import { Route } from "react-router";
import * as React from "react";

import Excel from "../components/Excel";

export default (
  <Route handler={Excel} path="/" name="excel" />
);

这是前端的入口点

import * as React from "react";
import * as Router from "react-router";

import routes from "./shared/routes";

Router.run(routes, Router.HistoryLocation, (Root, state) => {
  React.render(<Root />, document.getElementById('app'));
});

我的问题是,当我启动应用程序时,我收到此警告:

Warning: Failed propType: Required prop `header` was not specified in `Excel`. Check the render method of `Router`.
Warning: Failed propType: Required prop `initialData` was not specified in `Excel`. Check the render method of `Router`.

因此出错。你知道在这种情况下传递道具的正确方法是什么?

修改

错误消息

Uncaught SyntaxError: Unexpected token &
1../components/Excel @ bundle.js:4s @ bundle.js:1e @ bundle.js:1(anonymous function) @ bundle.js:1

1 个答案:

答案 0 :(得分:1)

与您同构的应用程序的生命周期是,首先,服务器运行JS代码并返回呈现结果的HTML字符串表达式。它将它安装到DOM,然后加载您的前端应用程序。当然DOM应该是相同的,所以它不需要真正重新渲染任何东西,但它确实将所有JS事件处理程序,React代码等安装到窗口中。

它仍将处理Router.run方法并匹配路由,但它将与从服务器加载的页面相同。但是,在此之后,前端必须复制服务器端功能(即获取数据,传递给路由组件)。

因此,在您的前端代码中,您需要获取通常在服务器上执行的所需数据,并将其作为道具传递给<Root />组件。

查看此演示,特别是app/server.js(服务器端渲染)和app/client.js(客户端渲染)。希望这有帮助!

React Router Mega Demo