4.react 路由管理

384 阅读1分钟

参考:cloud.tencent.com/developer/a…

juejin.cn/post/691149…

react-router-config用于静态路由配置,属于react-router的一个插件,主要用于集中管理路由配置

1.创建router.ts文件或者文件嵌套,编写以下代码:

//编写基本的路由路线,path为路径,component为对应渲染的组件,exact属性决定是否精准匹配


export default [{

    component: Layout,

    routes: [{

        path: '/',

        component: Teenager,

        exact: true

    },

    {

        path: '/forget_password',

        component: ForgetPassword,

        exact: true

    },

    {

        path: '/unlock_password',

        component: UnlockPassword,

        exact: true

    },]

}];


2.接着在App组件中引入导出的路由表,从 react-router-config 中解构 renderRoutes 函数,通过 renderRoutes 函数渲染出路由表的对应组件

ReactDOM.render(//react-dom

    <Router>//react-router-dom

    <Provider store={store}>//react-redux存储

    <WModal />//自定义弹窗?

    {renderRoutes(routesConfig)}//react-router-config路由配置

    </Provider>

    </Router>,

    document.getElementById('app')//由于嵌套属于绑定在app下组合

);

3. 嵌套路由

正常的业务必定有前套路由的使用,先在路由表中添加routes属性,值为RouteConfig[]


    {

        path: "/",

        component: Home,

        exact: true,

    },

    {

        path: "/group",

        component: Group,

        routes: [ //此处添加嵌套路由

            {

            path: "/group/detail",

            component: GroupDetail,

            },

            ],

            },

            {

            path: "/about",

            component: About,

            },

];

4.关于路由守卫

在使用 Vue 或者 Angular 的时候,框架提供了路由守卫功能,但是React Router 4.0 采用了声明式的组件,路由即组件,要实现路由守卫功能,就得我们自己去写了。react实现路由拦截的基本思路还是利用Route 的render函数。通过判断拦截条件来实现不同的组件的跳转,从而实现拦截。可以自己封装一个高阶组件去完成参考:www.jianshu.com/p/677433245…