如何使用反应路由器处理带有延迟加载组件的面包屑?

时间:2015-12-17 23:03:57

标签: javascript react-router

我一直在寻找一个关于如何为延迟加载的路由处理面包屑的示例。我已经能够在服务器上正常工作,但是无法获取客户端上由getComponent()屏蔽的延迟加载组件。如何访问异步组件?

routes.js

module.exports = {
    component: Layout,
    childRoutes: [
        {
            path: '/',
            component: App,
            childRoutes: [
                {
                    path: '/lazy',
                    component: Lazy, // Lazy loaded component
                }
            ]
        }
    ]
};

Lazy.js

// Server polyfill
if (typeof require.ensure !== 'function') { require.ensure = function(d, c) { c(require) }; }

module.exports = {
    path: 'detail',
    getComponent: function(location, cb) {
        require.ensure([], (require) => {
            cb(null, require('./components/Detail')); //Component I want to access
        });
    }
};

Breadcrumbs.js

import React, { Component, PropTypes } from 'react';

class Breadcrumbs extends Component {
    static propTypes = {
        routes: PropTypes.array.isRequired
    };

    render() {
        const { routes } = this.props;
        return (
            <ol className="breadcrumbs">
                {routes.map((route, index) => {
                    return (
                        <li key={index}>{route.component.title}</li>
                    );
                })}
            </ol>
        );
    }
}

export default Breadcrumbs;

问题是异步路由如下:

{
    path: 'detail',
    component: {
        getComponent: function()
    }
}

而不是:

{
    path: 'detail',
    component: {
        title: 'Lazy Detail'
    }
}

1 个答案:

答案 0 :(得分:0)

而不是你拥有的东西,我只是将title放在路由对象而不是组件上 - 这应该可以解决你的问题并为你提供更多的灵活性。

如果必须这样做,可以使用自定义RoutingContext,但这是一个半私有API,可能会在v1.1.x中消失。一般来说,在<Route>上定义它似乎更清晰。