页面路由组件

import Badge from ‘../../../src/components/Badge’

页面路由组件对应一个路由,进入对应路由时会渲染该组件,同时离开该路由的时候也会卸载该组件,相比于普通的 React 组件,页面路由组件会有一些增强的能力,比如可以定义一些配置项、默认会携带一些 props 等。

页面组件配置项

框架为页面级组件提供了一些特殊的配置项,让页面级组件可以快速拥有一些能力。支持两种配置方式:

  • 中心化配置在 src/routes.ts
  • 去中心化配置在每个页面组件入口 tsx 中

1. 中心化配置在 src/routes.ts 中(推荐)

对于使用配置式路由的开发者,推荐中心化配置在 src/routes.ts 中,管理起来更加方便:

  1. import UserLogin from '@/pages/UserLogin';
  2. export default [
  3. {
  4. path: '/login',
  5. component: UserLogin,
  6. + pageConfig: {
  7. + title: '登录页面',
  8. + },
  9. },
  10. ];
  11. export default routerConfig;

pageConfig 支持的配置项:

  • title: String,配置页面标题
  • scrollToTop: Boolean,默认 false,进入页面时是否要滚动到顶部
  • auth: String[],配置页面准入权限角色列表
  • errorBoundary: Boolean,默认 false,是否为页面组件包裹 ErrorBoundary
  • keepAlive: Boolean,由 plugin-keep-alive 插件扩展,默认 true
  • spm: String,由 plugin-spm 插件扩展

2. 去中心化配置在每个页面组件上

对于使用文件约定路由的项目,只能去中心化配置在每个页面组件上。

  1. // src/pages/Home/index.tsx
  2. import React from 'react';
  3. const Home = () => {
  4. return (
  5. <div>Home</div>
  6. );
  7. };
  8. + Home.pageConfig = {
  9. + title: 'Home'
  10. + };
  11. export default Home;

页面组件默认 props

对于路由组件(即页面级组件),可通过组件 props 获取到如下属性:

  • location:当前路由的 location 对象,包含 pathnamesearchhashstate 属性
  • history:详见 history api
  • searchParams:当前 URL 的查询参数对象(需要开启 parseSearchParams
  • match:当前路由和 URL match 后的对象,包含 pathurlparamsisExact 属性
  • pageConfig:在 routes.ts 中配置的页面 pageConfig 属性
  1. // src/pages/Home/index.tsx
  2. export default function Home(props) {
  3. const { location, history, searchParams, match, pageConfig } = props;
  4. const { foo } = pageConfig;
  5. console.log(foo); // => bar
  6. return <>Home</>;
  7. }

对于非路由组件,组件内如想获取上述属性需要借助 useHistory, useLocation, useParams, withRouter 等 API。

页面组件静态方法

通过 Page.getInitialProps() 在 SSR/SSG 的时候异步获取初始属性:

  1. // src/pages/Home/index.tsx
  2. import React from 'react';
  3. const Home = ({ stars }) => {
  4. return (
  5. <div>Home stars: {stars}</div>
  6. );
  7. };
  8. + Home.getInitialProps = async (ctx) => {
  9. + const res = await request.get('https://api.github.com/repos/alibaba/ice');
  10. + return { stars: res.data.stargazers_count };
  11. + }
  12. export default Home;

通过 Page.getStaticPaths() 指定 SSG 时动态路由的页面需要渲染出哪些具体的路由页面:

  1. // src/pages/Project/index.tsx
  2. import React from 'react';
  3. import { useParams } from 'ice';
  4. const Project = () => {
  5. const params = useParams();
  6. return (
  7. <div>Project id: {params.id}</div>
  8. );
  9. };
  10. + Project.getStaticPaths = async () => {
  11. + return ['/project/1', 'project/100'];
  12. + }
  13. export default Project;