react自動處理路由

furfur-jiang發表於2020-11-13

為了避免一個一個route,提高開發效率
自動掃描views資料夾下的檔案,我的要求的含list和index的掃下來

注意:若使用antd的Menu標籤,此處path必須與Menu.item的key屬性完全吻合

import React from 'react'
import { Switch } from 'react-router-dom'
import PrivateRouter from '../privateRouter/Index';
// 代替路由的錄入
// 自動處理路由
const files = require.context('../../views', true, /\.js$/)
// 宣告元件物件
const Components = [];
// 遍歷需要轉成導航欄的頁面views
files.keys().map(item => {
    let url = item.slice(1).toLowerCase().split('.')[0]
    if (/list/.test(url) || url.includes('index')) {
        const component = files(item).default
        const path = `/admin${url}`;
        Components.push(
            {
                path,
                component
            }
        )
    }
})
class AutoMenu extends React.Component {
    constructor(props) {
        super(props)
        this.state = {}
    }
    render() {
        return (
            <Switch>
                {Components.map((item) => {
                    return <PrivateRouter exact key={item.path} path={item.path} component={item.component} />
                })}
            </Switch>
        )
    }
}

export default AutoMenu

privateRouter封裝

import React from 'react'
import { Route,Redirect } from 'react-router-dom'

//配置私有路由,阻攔未登入的使用者
const privateRouter = ({ component: Component, ...rest }) => {
  let isLogin = localStorage.getItem('userId') 
  return (
    <Route
      {...rest}
      render={routeProps => (
        isLogin?
        <Component {...routeProps} />: <Redirect to="/" />
      )}
    />
  );
}


export default privateRouter

相關文章