服务器端渲染与反应路由器与数据获取

server side render with react router with data fetch

我正在升级到 React Router 版本 1,无法让我的代码的数据获取端在服务器上运行,即初始服务器端渲染。

我想做的是根据所选路线从服务器获取数据。每个组件都有一个 static fetchData 方法 以及一个全局数据方法,我构建数据然后传递到路由配置中定义的控制器视图组件。

我的代码如下:

match({routes, location: req.url}, (err, redirectLocation, renderProps) => {

  fetchData(renderProps).then((data) => {
      //page specific data
      return data;
    }).then((data) => {
      //global data
      getGlobalData().then((appData) => {

        data.app = appData;

        data = Immutable.fromJS(data);

        let templateLocals = {
          "data": data
        };    console.log('trying to render');
      templateLocals.content = renderToString(
    <RoutingContext {...renderProps} data={data}/>
  );
  res.send(layout(templateLocals));
    });

  });
});

我想像以前一样用 <Handler> pre V1.0 做的是将我的数据作为道具传递到应用程序中(我可以看到数据是正确的,当我将它传递到 RoutingContext 组件时)。但是我从 RoutingContext 模块中看到的是实现不允许这样做。它只获取 history,location,params,route,routeParams,routes 而不是任何 custom props.

服务器端渲染的示例没有到此为止,但我很想知道在升级时我应该如何处理这样的示例?

提前致谢

查看 async-props 存储库,它提供了一个示例以及用于处理同构数据获取的实用程序:https://github.com/rackt/async-props.

如果您使用的是 Redux,请同时查看 https://github.com/Rezonans/redux-async-connect 它类似于 AsyncProps,但更适合使用 Redux

的项目