如何使用react路由器处理带有lazyloaded组件的面包屑

How do you handle breadcrumbs with lazyloaded components using react router?

本文关键字:组件 lazyloaded 面包 何使用 react 路由器 处理      更新时间:2023-09-26

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

路由.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
        });
    }
};

面包屑.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'
    }
}

我只想把title放在路由对象上,而不是组件上,这样可以解决您的问题,并给您更多的灵活性。

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