创建index.js
const files = require.context('../components', true, /\.jsx$/);
const pages = [];
files.keys().forEach(key => {
let i = key.replace(/(\.\/|\.jsx)/g, '');
if(i !== 'index'){
let component = files(key).default;
let path = i.indexOf('/index') !== -1 ? i.split('/index')[0] : i;
pages.push({
path,
component
});
}
});
export default pages;
创建router.js
import React from 'react';
import {Switch, Route } from 'react-router-dom';
import Pages from './index';
/* 视图组件 */
import Index from '../components/index';
class RouteIndex extends React.Component {
render() {
console.log(Pages);
return (
<Switch>
<Route path="/" exact component={Index}></Route>
{
Pages.length > 0 && Pages.map((item, index) => {
return (
<Route
key={index}
exact
path={`/${item.path}`}
component={item.component}
/>
)
})
}
</Switch>
);
}
}
export default RouteIndex;