• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Smash
V2EX  ›  程序员

求一个 React Router 路由守卫的现成轮子

  •  
  •   Smash · Jul 26, 2021 · 2839 views
    This topic created in 1797 days ago, the information mentioned may be changed or developed.

    第一次写 React,官方的路由没有封装守卫

    由于路由这块我还不是很熟悉,求一个现成的轮子.

    Supplement 1  ·  Jul 27, 2021
    去 github 转了一圈,发现也没有封装得太好的,行了, 我自己封装.
    7 replies    2021-07-27 11:20:13 +08:00
    shilianmlxg
        1
    shilianmlxg  
       Jul 27, 2021
    如果是 hooks 是有轮子的 useRouter
    如果不是 那我也蹲一个
    ericgui
        2
    ericgui  
       Jul 27, 2021
    似乎是没有的
    SmiteChow
        4
    SmiteChow  
       Jul 27, 2021
    这玩意自己写不就几行代码么?

    ```app.jsx
    import styles from '../css/app.cssm' assert { type: "css" }
    import SideBar from './side-bar.jsx';
    import ZYTable from './zy-table.jsx';
    import BatchOperateZY from './batch-operate-zy.jsx';

    const tabs = {
    table: '资源管理',
    batch: '批量操作',
    };

    export default function App(props) {
    let hash = location.hash;
    const [tab, setTab] = React.useState(hash === '' ? 'table' : hash.substr(1));

    React.useEffect(() => {
    document.title = `ZYMS 画廊 - ${tabs[tab]}`
    document.location.hash = `#${tab}`
    }, [tab])

    return <div className={styles.flex}>
    <SideBar tabs={tabs} tabName={tab} showTab={(name) => setTab(name)}/>
    <div className={`${styles['tab-container']}`}>
    {tab === 'table' && <ZYTable/>}
    {tab === 'batch' && <BatchOperateZY/>}
    </div>
    </div>
    }
    ```
    Smash
        5
    Smash  
    OP
       Jul 27, 2021
    @SmiteChow 我想做成统一配置类似 Vue,配置路由 React Router 支持,但是在配置路由上的守卫需要自己实现.

    你的示例分散在各个 component 中,不方便管理和维护.
    Carseason
        6
    Carseason  
       Jul 27, 2021
    hooks 的 Router 组件有个 render 的钩子来实现
    Smash
        7
    Smash  
    OP
       Jul 27, 2021
    @Carseason 谢谢,已经在文档看到了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2968 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 14:04 · PVG 22:04 · LAX 07:04 · JFK 10:04
    ♥ Do have faith in what you're doing.