路由的React路由器调节

时间:2015-07-24 01:29:18

标签: javascript reactjs react-router url-routing react-router-component

我使用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
        }   
    });
}); 

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

2 个答案:

答案 0 :(得分:1)

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

state回调中的Router.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。祝你好运!

答案 1 :(得分:0)

if (state.routes.length === 0 || state.routes[state.routes.length - 1].isDefault) { 
    // stuff here 
}

那更好。