React之react-router 6 的使用方法

本文详细介绍了React Router v6的使用方法,包括创建自定义Route组件、设置基础路由、在App中引入路由、页面内跳转、baseUrl的使用以及与v5版本的对比。通过示例代码展示了如何创建路由组件、引入页面组件以及实现页面间的导航。同时,还提及了在v5中设置loading组件和history组件的方式。
摘要由CSDN通过智能技术生成

router 6 的使用方法

一、创建route组件

import React, { FC } from 'react';
import { Route as RRoute, RouteProps as RRouteProps } from 'react-router-dom';

export type RouteProps = {
  children: RRouteProps['element'];
} & RRouteProps;
const RouteComponent: FC<RouteProps> = ({ ...props }) => (
  <RRoute path={props.path} element={props.children} />
);
export default RouteComponent;

二、路由组件

(1)基础路由组件

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
//下面这两个都是页面中的路由逻辑关系,我写到一个文件里去了
import AdultRoutes from 'views/account-adult/routes';
import ConfigRputes from 'views/account-config/routes';

const Main = (): React.ReactElement => (
  <BrowserRouter>
    <Routes>
      <Route path="/*" element={AdultRoutes} />
      <Route path="/config/*" element={ConfigRputes} />
    </Routes>
  </BrowserRouter>
);

export default Main;

(2)页面组件

AdultRoutes为例子

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import BaseLayout from 'layouts/Base';
import BaseLogin from 'src/components/base-login';

const SearchInactive = React.lazy(() => import('views/account-adult/search-inactive'));
const SearchAll = React.lazy(() => import('views/account-adult/search-all'));
const InactiveDetail = React.lazy(
  () => import('views/account-adult/search-inactive/components/detail'),
);
const AdultRoutes = (
  <Routes>
    <Route
      path="/"
      element={
        <BaseLogin>
          <BaseLayout>
            <React.Suspense fallback={<>loading...</>}>
              <SearchAll />
            </React.Suspense>
          </BaseLayout>
        </BaseLogin>
      }
    />
    <Route
      path="inactive"
      element={
        <BaseLogin>
          <BaseLayout>
            <React.Suspense fallback={<>loading...</>}>
              <SearchInactive />
            </React.Suspense>
          </BaseLayout>
        </BaseLogin>
      }
    />
    <Route
      path="/inactive/detail"
      element={
        <BaseLogin>
          <BaseLayout>
            <React.Suspense fallback={<>loading...</>}>
              <InactiveDetail />
            </React.Suspense>
          </BaseLayout>
        </BaseLogin>
      }
    />
  </Routes>
);

export default AdultRoutes;

所以这里又三种路由分别对应

/ ----> SearchAll
/inactive.  ------> SearchInactive
/inactive/detail. -------> InactiveDetail

三、在app中引入

import React from 'react';
import { ConfigProvider } from 'antd';
import moment from 'moment';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import Router from './router';
import 'moment/locale/zh-cn';

moment.locale('zh-cn');

function App() {
  return (
    <div className="App">
      <ConfigProvider locale={zh_CN}>
        <Router />
      </ConfigProvider>
    </div>
  );
}

export default App;

四、页面中进行跳转

在页面中需要跳转,或者需要往url push信息时,直接使用useNavigate

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();

  const handleSubmit = useCallback(
    values => {
      navigate({
        pathname: '/inactive',
        search: queryString.stringify({
          ...values,
          pageIndex: 1,
          pageSize: 10,
        }),
      });
    },
    [navigate],
  );

search使用

import { useLocation } from 'react-router-dom';

const location = useLocation(); //是给search使用
const search = useMemo(() => queryString.parse(location.search), [location.search]);

//还可以在函数中使用,不做赘述
const pageIndex = +search.pageIndex || 1; //可以直接获取,+代表数字,
const pageSize = +search.pageSize || 10;

五、baseUrl使用+重定向

import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import AssetsRoutes from 'views/assets-center/routes';
import LabelRputes from 'views/label-manage-center/routes';

const Main = (): React.ReactElement => (
  <BrowserRouter basename="api_asset_plt"> //baseUrl
    <Routes>
    //当输入/ 重定向到/assets
      <Route path="/" element={<Navigate to="/assets" replace />} />
      <Route path="/assets/*" element={AssetsRoutes} />
      <Route path="/label/*" element={LabelRputes} />
    </Routes>
  </BrowserRouter>
);

export default Main;

router 5及以下

一、设置loading组件

import React, { FC, memo, ComponentClass, ReactNode, Suspense } from 'react'
import { Route as RRoute, RouteProps as RRouteProps } from 'react-router-dom'
import { Spin } from 'antd'
// const ErrorPage = React.lazy(() => import('layouts/Error'));

export type RouteProps = {
  isAuth?: boolean
  fallback?: NonNullable<ReactNode> | null
  lazy?: boolean
  layout?: ComponentClass<any> | FC<any>
} & RRouteProps
export const Route: FC<RouteProps> = ({
  lazy = true,
  isAuth = true,
  fallback,
  layout: Layout,
  children,
  ...props
}) => {
  const Fallback = fallback ? (
    fallback
  ) : (
    <div className={'spin-loading'}>
      <Spin tip={'加载中...'} />
    </div>
  )
  const Component = lazy ? (
    <Suspense fallback={Fallback}>{children}</Suspense>
  ) : (
    children
  )
  return (
    <RRoute {...props}>
      <Suspense fallback={Fallback}>
        {Layout ? <Layout>{Component}</Layout> : Component}
      </Suspense>
    </RRoute>
  )
}

export default memo(Route)

二、设置history组件

import { createBrowserHistory } from 'history'

const history = createBrowserHistory()

export default history

三、路由组件

这里可以直接导入页面组件

import React from 'react';
import { Router, Switch } from 'react-router-dom';
import Route from './route';
import history from './history';
import BaseLayout from 'layouts/Base';

//import
const StatisticsList = React.lazy(() => import('views/statistics/list'));
const ErrDetails = React.lazy(() => import('views/statistics/errDetails'));

const Main = (): React.ReactElement => {
  return (
    <Router history={history}>
      <Switch>
        <Route path={'/'} layout={BaseLayout} exact>
          <StatisticsList />
        </Route>
        <Route path={'/err/detail'} layout={BaseLayout}>
          <ErrDetails />
        </Route>
      </Switch>
    </Router>
  );
};

export default Main;


  1. 可以直接看出6省略了createBrowserHistory的用法
  2. 而且也不需要自己写加载的组件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值