首页指南参考教程

错误处理

了解使用 Expo Router 时如何处理应用中不匹配的路由和错误。


本指南指定了使用 Expo Router 时如何处理应用中不匹配的路由和错误。

¥This guide specifies how to handle unmatched routes and errors in your app when using Expo Router.

未匹配的路由

¥Unmatched routes

原生应用没有服务器,因此从技术上讲不存在 404。但是,如果你要实现通用路由,那么处理丢失的路由是有意义的。这是针对每个应用自动补齐的,但你也可以对其进行自定义。

¥Native apps don't have a server so there are technically no 404s. However, if you're implementing a router universally, then it makes sense to handle missing routes. This is done automatically for each app, but you can also customize it.

app/[...unmatched].js
import { Unmatched } from 'expo-router';
export default Unmatched;

这将渲染默认的 Unmatched。你可以导出任何想要渲染的组件。我们建议提供 / 的链接,以便用户可以导航回主屏幕。

¥This will render the default Unmatched. You can export any component you want to render instead. We recommend having a link to / so users can navigate back to the home screen.

错误处理

¥Error handling

Expo Router 支持微调错误处理,以便在未来实现更加有态度的数据加载策略。

¥Expo Router enables fine-tuned error handling to enable a more opinionated data-loading strategy in the future.

你可以从任何路由导出嵌套的 ErrorBoundary 组件,以使用 反应错误边界 拦截和格式化组件级错误:

¥You can export a nested ErrorBoundary component from any route to intercept and format component-level errors using React Error Boundaries:

app/home.tsx
import { View, Text } from 'react-native';

export function ErrorBoundary(props: ErrorBoundaryProps) {
  return (
    <View style={{ flex: 1, backgroundColor: "red" }}>
      <Text>{props.error.message}</Text>
      <Text onPress={props.retry}>Try Again?</Text>
    </View>
  );
}

export default function Page() { ... }

当你导出 ErrorBoundary 时,路由将被有效的 React Error Boundary 封装:

¥When you export an ErrorBoundary the route will be wrapped with a React Error Boundary effectively:

Virtual
function Route({ ErrorBoundary, Component }) {
  return (
    <Try catch={ErrorBoundary}>
      <Component />
    </Try>
  );
}

ErrorBoundary 不存在时,错误将被抛出到最近的父级的 ErrorBoundary

¥When ErrorBoundary is not present, the error will be thrown to the nearest parent's ErrorBoundary.

API

ErrorBoundaryProps

每个 ErrorBoundary 都传递以下属性:

¥Each ErrorBoundary is passed the following props:

  • 错误:Error — 引发的错误。

    ¥error: Error — The error that was thrown.

  • 重试:() => Promise<void> — 将重新渲染路由组件的函数。

    ¥retry: () => Promise<void> — A function that will rerender the route component.

ErrorBoundary

你还可以使用默认的 ErrorBoundary 组件来实现快速 UI:

¥You can also use the default ErrorBoundary component for a quick UI:

app/home.tsx
// Re-export the default UI
export { ErrorBoundary } from 'expo-router';

尚未完成的

¥Work in progress

React Native LogBox 需要不那么激进地渲染,以便开发时出现错误。目前,它显示 console.errorconsole.warn。然而,理想情况下它应该只显示未捕获的错误。

¥React Native LogBox needs to be presented less aggressively to develop with errors. Currently, it shows for console.error and console.warn. However, it should ideally only show for uncaught errors.

Expo 中文网 - 粤ICP备13048890号