首页 文章

React-router v1.0;将道具传递到服务器上的应用程序

提问于
浏览
0

在react-router 0.13中,您可以将props传递到路由处理程序中

serverApp.get('/*', function(req, res) {
  Router.run(AppRoutes, req.url, function(Handler, state) {
    var markup = React.renderToString(
      <Handler path={req.url} myProps={myProps}/>
    );
    res.send('<!DOCTYPE html>' + markup);
  });
});

现在使用react-router v1.0,已被 match()RoutingContext 替换 . 我无法让它发挥作用 . 我的代码如下:

serverApp.get('/*', function(req, res) {
  match({routes: AppRoutes, location: req.url},
    (error, redirectLocation, renderProps) => {
      var markup;

      if (error) {
        res.status(500).send(error.message);
      } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      } else if (renderProps) {
        var myApp = React.cloneElement(<RoutingContext {...renderProps} />, {myProps: 'OK'});
        markup = renderToString(myApp);
        res.status(200).send('<!DOCTYPE html>' + markup);
      } else {
        res.status(404).send('Not found');
      }
    }
  );
});

这是我认为应该工作的,但没有成功 . 我通过在组件的render方法中注销其他prop来测试它,并将其设置在h1标记中 .

关于我在这里做错了什么的想法?非常感激 .

相关:https://github.com/rackt/react-router/issues/1369

1 回答

  • 0

    您必须将方法 createElement 传递给 RoutingContext . 在 createElement 方法中,您可以访问将返回的组件 . 在这里,您可以添加可用于安装的每条路线的外部道具 .

    服务器:

    serverApp.get('/*', function(req, res) {
      match({routes: AppRoutes, location: req.url},
        (error, redirectLocation, renderProps) => {
          var markup;
          var myApp;
          var createElement = function(Component, props) {
            return <Component {...props} myProps="OK"/>;
          };
    
          if (error) {
            res.status(500).send(error.message);
          } else if (redirectLocation) {
            res.redirect(302,
              redirectLocation.pathname + redirectLocation.search);
          } else if (renderProps) {
            myApp = (
              <RoutingContext
                {...renderProps}
                createElement={createElement}
              />
            );
            markup = renderToString(myApp);
            res.status(200).send('<!DOCTYPE html>' + markup);
          } else {
            res.status(404).send('Not found');
          }
        }
      );
    });
    

    反应应用路线:

    var AppRoutes = (
      <Route component={AppTemplate} path="/">
        <Route component={OtherTemplate} path="/">
          <Route component={FirstPage} path="/first" />
        <Route />
      <Route />
    );
    

    导航到'/first'时,所有这3个组件都可以通过 this.props.myProps 访问myProps

    更实际的用例是将flux对象传递给应用程序(而不是简单的myProps =“OK”) .

相关问题