安裝wordpress linux長沙網(wǎng)站推廣seo
文章目錄
- 前言
- 一、路由配置和懶加載lazy的使用
- 二、TS版本Error Boundary組件封裝
- 三、在layout組件中使用Suspense組件和錯誤邊界組件
- 總結(jié)
前言
本文將詳細介紹項目中的頁面路由配置和異步組件懶加載處理,以提高用戶體驗,實現(xiàn)過渡效果。
一、路由配置和懶加載lazy的使用
(1)在React中,通常使用Suspense和lazy函數(shù)來實現(xiàn)懶加載,比如使用一個加載動畫。
(2)通過這種方式,可以減少初始加載時間,提高應(yīng)用程序的性能和響應(yīng)速度。
// @/router/index.ts
import { lazy } from "react";
import { Navigate, RouteObject } from "react-router-dom";
const Layout = lazy(() => import("@/layout"));
const NotFound = lazy(() => import("@/pages/NotFound/index"));
const Home = lazy(() => import("@/pages/Home"));
const NervosDao = lazy(() => import("@/pages/NervosDao"));
const Tokens = lazy(() => import("@/pages/Tokens"));
const Xudts = lazy(() => import("@/pages/Xudts"));
const Charts = lazy(() => import("@/pages/Charts"));
const FeeRateTracker = lazy(() => import("@/pages/FeeRateTracker"));
const routes: RouteObject[] = [{path: "/",element: <Navigate to={`/zh/home`} />,},{path: "/:locale",element: <Navigate to={`/zh/home`} />,},{path: "/:locale",element: <Layout />,children: [// 其他子路由配置{path: "/:locale/home",element: <Home />,},{path: "/:locale/nervosdao",element: <NervosDao />,},{path: "/:locale/tokens",element: <Tokens />,},{path: "/:locale/xudts",element: <Xudts />,},{path: "/:locale/charts",element: <Charts />,},{path: "/:locale/fee-rate-tracker",element: <FeeRateTracker />,},],},{path: "/404",element: <NotFound />,},{path: "*",element: <Navigate to={`/404`} />,},
];
export default routes;
二、TS版本Error Boundary組件封裝
// @/components/ErrorBoundary/index.jsx
import * as React from "react";
interface PropsType {children: React.ReactNode;
}
interface StateType {hasError: boolean;Error?: null | Error;ErrorInfo?: null | React.ErrorInfo;
}
export class ErrorBoundary extends React.Component<PropsType, StateType> {constructor(props: PropsType) {super(props);this.state = {hasError: false,Error: null,ErrorInfo: null,};}//控制渲染降級UIstatic getDerivedStateFromError(error: Error): StateType {return { hasError: true };}//捕獲拋出異常componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {//傳遞異常信息this.setState((preState) => ({ hasError: preState.hasError, Error: error, ErrorInfo: errorInfo }));//可以將異常信息拋出給日志系統(tǒng)等等//do something....}render() {const { hasError, Error, ErrorInfo } = this.state;const { children } = this.props;//如果捕獲到異常,渲染降級UIif (hasError) {return (<div><h1>{`Error:${Error?.message}`}</h1><details style={{ whiteSpace: "pre-wrap" }}>{ErrorInfo?.componentStack}</details></div>);}return children;}
}
三、在layout組件中使用Suspense組件和錯誤邊界組件
// @/layout/index.tsx
import { Suspense } from "react";
import { ErrorBoundary } from "@/components/ErrorBoundary";
const LayOut = () => {// ....return (// ...<Suspense fallback={<span>loading...</span>}><ErrorBoundary><Outlet /></ErrorBoundary></Suspense>// ...);
};
export default LayOut;
總結(jié)
下一篇講【國際化配置】。關(guān)注本欄目,將實時更新。