3

我正在使用 React Router 进行服务器端渲染,我想在某个 Route 上运行一个特殊操作,实际上是在 DefaultRoute 上。我应该如何为此创造条件?我尝试了以下代码:

var React = require("react");
var Router = require("react-router");

var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;

var routes = [
    React.createElement(Route, {name: "root", path: "/", handler: Root},
        React.createElement(DefaultRoute, {handler: Default})
    )
]

var Default = React.createClass({
    displayName: "Default",
    render: function () {
        return React.createElement("h2", null, "Default");
    }
});

var Root = React.createClass({
    displayName: "App",
    render: function () {
        return (
            React.createElement(RouteHandler, null)
        );
    }
});

app.get('*', function (req, res) {
    Router.run(routes, req.path, function (Root, state) {
        if (React.createElement(Root, null).constructor.displayName === 'Default'){
            //run specific action
        }   
    });
}); 

但是我无法以这种方式获取组件的名称。有没有其他方法可以识别我在默认路由上?

4

2 回答 2

1

我还在使用 React-Router 进行同构服务器端路由。

回调中的statepropRouter.run包含活动路由。您可以执行以下操作:

// states.routes returns the nested routes that your path matches.
// This will return the last route. 
if (state.routes[state.routes.length-1].isDefault) {
  // stuff here
  // you also have access to the onEnter method and the handler (component) in the route too.
}

在此处查看 API 文档:http ://rackt.github.io/react-router/#Router.run 。祝你好运!

于 2015-07-24T12:28:49.547 回答
0
if (state.routes.length === 0 || state.routes[state.routes.length - 1].isDefault) { 
    // stuff here 
}

那就更好了。

于 2015-08-03T14:08:03.640 回答