React:在应用程序中处理错误(Error Boundary)
引言
在这篇文章中,我们将探讨如何在React中自带的处理错误。React提供了一种错误边界机制,称为Error Boundary,可以用来捕获应用程序中发生的错误。接下来,我们将详细介绍如何使用Error Boundary进行错误处理。
环境
- 操作系统:Windows 10
- Vite版本:v2.7.2
- Node版本:v19.0.0
- React版本:v19.0.0
- TypeScript版本:v5
创建一个没有错误的示例程序
首先,我们将创建一个没有错误的示例程序。

以下是具体代码:
main.tsx
import App from "./App";
export default function Home() {
return <App />;
}
components/App.tsx
import Page1 from "@/components/Page1";
import Page2 from "@/components/Page2";
import Page3 from "@/components/Page3";
export default function App() {
return (
<>
<Page1 />
<Page2 />
<Page3 />
</>
);
}
components/Page1.tsx
export default function Page1() {
return (
<div style={
{ backgroundColor: "lightblue", paddingBottom: "20px" }}>
<h3>Page1</h3>
</div>
);
}
components/Page2.tsx
export default function Page2() {
return (
<div style={
{ backgroundColor: "yellow", paddingBottom: "20px" }}>
<h3>Page2</h3>
</div>
);
}
components/Page3.tsx
import Page3Child from "./Page3Child";
export default function Page3() {
return (
<div style={
{ backgroundColor: "grey", paddingBottom: "20px" }}>

最低0.47元/天 解锁文章
1693

被折叠的 条评论
为什么被折叠?



