文章目录
- 前言
- 一、路由配置和懒加载lazy的使用
- [二、TS版本Error Boundary组件封装](#二、TS版本Error Boundary组件封装)
- 三、在layout组件中使用Suspense组件和错误边界组件
- 总结
前言
本文将详细介绍项目中的页面路由配置和异步组件懒加载处理,以提高用户体验,实现过渡效果。
一、路由配置和懒加载lazy的使用
(1)在React中,通常使用Suspense和lazy函数来实现懒加载,比如使用一个加载动画。
(2)通过这种方式,可以减少初始加载时间,提高应用程序的性能和响应速度。
c
// @/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组件封装
c
// @/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,
};
}
//控制渲染降级UI
static getDerivedStateFromError(error: Error): StateType {
return { hasError: true };
}
//捕获抛出异常
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
//传递异常信息
this.setState((preState) => ({ hasError: preState.hasError, Error: error, ErrorInfo: errorInfo }));
//可以将异常信息抛出给日志系统等等
//do something....
}
render() {
const { hasError, Error, ErrorInfo } = this.state;
const { children } = this.props;
//如果捕获到异常,渲染降级UI
if (hasError) {
return (
<div>
<h1>{`Error:${Error?.message}`}</h1>
<details style={{ whiteSpace: "pre-wrap" }}>{ErrorInfo?.componentStack}</details>
</div>
);
}
return children;
}
}
三、在layout组件中使用Suspense组件和错误边界组件
c
// @/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;
总结
下一篇讲【国际化配置】。关注本栏目,将实时更新。