content.jsx
import React from 'react';
import Error from './Error'
import ErrorBoundary from './handle'
export default class Parent extends React.Component {
state = {
count: 0
}
increament = () => {
this.setState({
count: this.state.count + 1
})
}
decreament = () => {
this.setState({
count: this.state.count - 1
})
}
render() {
return (
<div>
<h1>这是一个标题</h1>
<p>{this.state.count}</p>
<ErrorBoundary render={(error, errorInfo) => <p>组件发生错误 {error.toString()}</p>}>
<Error />
</ErrorBoundary>
<button onClick={this.increament}>increment</button>
<button onClick={this.decreament}>decrement</button>
</div>
)
}
}
error.jsx , 故意写错 报异常
import React from 'react';
export default class Error extends React.Component {
render() {
return (
<ul>
{
null.map((el, index) => {
return (
<div>ddd</div>
)
})
}
</ul>
)
}
}
- 报错处理组件
import React from 'react';
export default class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: null,
errorInfo: null
}
componentDidCatch(error, errorInfo) {
this.setState({
hasError: true,
error: error,
errorInfo
})
}
render() {
if (this.state.hasError) {
return <div>{this.props.render(this.state.error, this.state.errorInfo)}</div>
}
return this.props.children
}
}