@xysfe/catch-react-error
Version:
react error boundaries
84 lines (77 loc) • 1.94 kB
Markdown
## How to use
1. install /catch-react-error
```bash
npm install /catch-react-error --save
```
2. Install ES7 Decorator babel plugin
```bash
npm install --save-dev /plugin-proposal-decorators
npm install --save-dev /plugin-proposal-class-properties
```
3. babel plugin configuration
```json
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
```
4. import /catch-react-error
```bash
import catchreacterror from "@xysfe/catch-react-error";
```
5. Use on class component
```js
class Count extends React.Component {
render() {
const { count } = this.props;
if (count === 3) {
throw new Error("count is three");
}
return <h1>{count}</h1>;
}
}
```
6. Use on functionc component
```js
function Count({ count }) {
if (count === 3) {
throw new Error("count is three");
}
return <h1>{count}</h1>;
}
const SaleCount = catchreacterror()(Count);
```
7. Add a CustomErrorBoundary component
```js
// First, create an normal Error Boundary Component and change it
class CustomErrorBoundary extends React.Component {
constructor (props) {
super (props);
this.state = {hasError: false};
}
static getDerivedStateFromError (error) {
return {hasError: true};
}
componentDidCatch (error, errorInfo) {
//do something as needed
reportToMyLogService (error, errorInfo);
}
render () {
if (this.state.hasError) {
return <h1> Something with my app,fallback ui. </ h1>;
}
}
return this.props.children;
}
}
// Second, pass it as the argument
class Count extends React.Component {}
```
or
```js
const SaleCount = catchreacterror(CustomErrorBoundary)(Count);
```