我有以下树形结构:
这是我的代码:
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进行映射时出现此错误:
毋庸置疑,相关文件的代码在每个目录中都是相同的,唯一的区别是它们的位置。
有什么想法吗?
谢谢!
答案 0 :(得分:0)
我对这个解决方案不满意,我不知道为什么会这样,但这有效
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;
}
有人告诉我为什么我必须这样做,我很感激。