了解 Expo 项目中的 Redbox 错误和堆栈跟踪。
使用 Expo 开发应用时,你会遇到 Redbox 错误或 Yellowbox 警告。这些日志记录经验由 React Native 中的日志框 提供。
¥When developing an application using Expo, you'll encounter a Redbox error or Yellowbox warning. These logging experiences are provided by LogBox in React Native.
¥Redbox error and Yellowbox warning
当致命错误阻止你的应用运行时,会显示 Redbox 错误。将显示黄框警告,通知你可能存在问题,你应该在发布应用之前解决它。
¥A Redbox error is displayed when a fatal error prevents your app from running. A Yellowbox warning is displayed to inform you that there is a possible issue and you should probably resolve it before shipping your app.
你还可以使用 console.warn("Warning message")
和 console.error("Error message")
自行创建警告和错误。触发红框的另一种方法是抛出错误而不捕获它:throw Error("Error message")
。
¥You can also create warnings and errors on your own with console.warn("Warning message")
and console.error("Error message")
. Another way to trigger the redbox is to throw an error and not catch it: throw Error("Error message")
.
¥Stack traces
当你在开发过程中遇到错误时,你将看到错误消息和堆栈跟踪,这是应用崩溃时最近进行的调用的报告。此堆栈跟踪会显示在你的终端和 Expo Go 应用中,或者如果你创建了开发版本。
¥When you encounter an error during development, you'll see the error message and a stack trace, which is a report of the recent calls your application made when it crashed. This stack trace is shown both in your terminal and the Expo Go app or if you have created a development build.
该堆栈跟踪非常有价值,因为它为你提供了错误发生的位置。例如,在下图中,错误来自文件 HomeScreen.js,并由该文件的第 7 行引起。
¥This stack trace is extremely valuable since it gives you the location of the error's occurrence. For example, in the following image, the error comes from the file HomeScreen.js and is caused on line 7 in that file.
当你查看该文件的第 7 行时,你将看到引用了一个名为 renderDescription
的变量。错误消息描述未找到该变量,因为该变量未在 HomeScreen.js 中声明。这是一个典型的例子,说明如果你花时间解读错误消息和堆栈跟踪,它们会有多大帮助。
¥When you look at that file, on line 7, you will see that a variable called renderDescription
is referenced. The error message describes that the variable is not found because the variable is not declared in HomeScreen.js. This is a typical example of how helpful error messages and stack traces can be if you take the time to decipher them.
调试错误是开发中最令人沮丧但又令人满意的部分之一。请记住,你永远不会孤单。Expo 社区以及 React 和 React Native 社区是你遇到困难时提供帮助的重要资源。其他人很可能也遇到了与你相同的错误。请务必阅读文档,搜索 forums、GitHub 问题 和 Stack Overflow。
¥Debugging errors is one of the most frustrating but satisfying parts of development. Remember that you're never alone. The Expo community and the React and React Native communities are great resources for help when you get stuck. There's a good chance someone else has run into your exact error. Make sure to read the documentation, search the forums, GitHub issues, and Stack Overflow.