• content.jsx

      1. import React from 'react';
      2. import Error from './Error'
      3. import ErrorBoundary from './handle'
      4. export default class Parent extends React.Component {
      5. state = {
      6. count: 0
      7. }
      8. increament = () => {
      9. this.setState({
      10. count: this.state.count + 1
      11. })
      12. }
      13. decreament = () => {
      14. this.setState({
      15. count: this.state.count - 1
      16. })
      17. }
      18. render() {
      19. return (
      20. <div>
      21. <h1>这是一个标题</h1>
      22. <p>{this.state.count}</p>
      23. <ErrorBoundary render={(error, errorInfo) => <p>组件发生错误 {error.toString()}</p>}>
      24. <Error />
      25. </ErrorBoundary>
      26. <button onClick={this.increament}>increment</button>
      27. <button onClick={this.decreament}>decrement</button>
      28. </div>
      29. )
      30. }
      31. }
    • error.jsx , 故意写错 报异常

    1. import React from 'react';
    2. export default class Error extends React.Component {
    3. render() {
    4. return (
    5. <ul>
    6. {
    7. null.map((el, index) => {
    8. return (
    9. <div>ddd</div>
    10. )
    11. })
    12. }
    13. </ul>
    14. )
    15. }
    16. }
    • 报错处理组件
    1. import React from 'react';
    2. export default class ErrorBoundary extends React.Component {
    3. state = {
    4. hasError: false,
    5. error: null,
    6. errorInfo: null
    7. }
    8. componentDidCatch(error, errorInfo) {
    9. this.setState({
    10. hasError: true,
    11. error: error,
    12. errorInfo
    13. })
    14. }
    15. render() {
    16. if (this.state.hasError) {
    17. return <div>{this.props.render(this.state.error, this.state.errorInfo)}</div>
    18. }
    19. return this.props.children
    20. }
    21. }