Dynamic React Router v4 仅适用于与路由声明相同的目录

Dynamic React Router v4 Only Works in Same Directory as Routes declaration

我的树结构如下:

这是我的代码:

const routes1 = [
    {path: '/home', loc: './home'},
    {path: '/about', loc: './about'},
    {path: '/contact', loc: './contact'}
];

const routes2 = [
    {path: '/home', loc: '../home'},
    {path: '/about', loc: '../about'},
    {path: '/contact', loc: '../contact'}
];

const routes3 = [
    {path: '/home', loc: '../home/index.js'},
    {path: '/about', loc: '../about/index.js'},
    {path: '/contact', loc: '../contact/index.js'}
];

export default class App extends Component {
    render() {
        return(
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' component={Home}/>
                    {this.getRoutes()}
                    <Route component={NotFound}/>
                </Switch>
            </BrowserRouter>
        )
    }

    getRoutes() {
        const res = [];
        // components in same directory as app.js
        routes1.map((route, idx) => {
            res.push(<Route path={route.path} 
                        key={idx} 
                        component={require(`${route.loc}`).default} />)
        });
        return res;
    }
}

当我通过数组 routes1

指向与 app.js 相同目录中的组件时,上面的代码有效

但是,通过 routes2 或 routes3 进行映射时出现此错误:

不用说了,每个目录下的相关文件的代码都是一样的,只是位置不同而已。

有什么想法吗?

谢谢!

我对这个解决方案不满意,我也不知道为什么会这样,但这很有效

const routes2 = [
    {path: '/home', loc: 'home'},
    {path: '/about', loc: 'about'},
    {path: '/contact', loc: 'contact'}
];


................



getRoutes() {
    .............
    // I removed the '../' from the array and added it to the require statement
        res.push(<Route path={route.path} key={idx} component={require(`../${route.loc}`).default} />)
    });
    return res;
}

有人告诉我为什么我必须这样做,我将不胜感激。