It is a very rare occasions, suddenly going to write a wrong boundary, readily checked the data and found that writing about React error boundaries rarely.
I suddenly realized that, you need some article to a record React exception error boundaries.
00 background
React 16+ offers Error Boundaries error boundaries.
Part of the UI JavaScript error should not undermine the entire application. To solve this problem React user, React 16 introduced a "boundary error (Error Boundaries)" new concept.
React boundary error component is, it can be captured anywhere tree subassembly JavaScript errors, the errors are logged, the UI and display an alternate , rather than the collapse of the entire tree assembly. Error boundary (Error Boundaries) to catch errors in the constructor rendering, life-cycle approach and the entire assembly tree's.
note
Error boundary can not capture the following error:
Event Processing ( learn more )
Asynchronous code (e.g. requestAnimationFrame setTimeout or callback function)
Side rendering service
Error boundary itself thrown out (rather than its sub-components)
01 combat
Let's use create-react-app build a case in point.
npx create-react-app react-error-boundary
cd react-error-boundary
Elevation start
If there npm start wrong, you can try to re-install node_modules
rm -rf node_modules
sudo cnpm i
There may be too slow with foreign npm source, you can use Taobao npm mirror.
npm config set registry https://registry.npm.taobao.org
npm config get registry // look at the mirror set yet
OK, after npm start successfully, localhost: 3000 you can see a demo page.
New File ErrorBoundary.js
New File ErrorComponent.js
The two components introduced in app.js, as follows,
<ErrorBoundary>
<ErrorComponent />
</ErrorBoundary>
Although componentDidCatch observed to capture the error, but the page is interrupted.
This is because npm start Error Boundary is still being given directly in the development model, development model.
Can look into the production mode effect,
npm run build
sudo cnpm i serve -g
serve -s build
You can see a parent component to capture the wrong sub-assemblies, and the page is displayed correctly.
Then we can make errors reported in componentDidCatch in.
May be included in a <ErrorBoundary /> components inside the root item, errors will subassembly is captured,
If you do not catch the error with ErrorBoundary with componentDidCatch, in window.onerror also can capture the error. The only good thing wrong with the boundary is to ensure the normal operation of the page.
02 What can not capture error
(1) Event Error
This.o above does not exist, an error, window.onerror can be captured, but not catch the error border.
(2) Asynchronous Code
(3) server to render their mistakes and errors border
Summarizes: React To understand the error border or under, although use is not particularly large.
Reproduced in: https: //www.jianshu.com/p/3ae9838ed51c