ErrorBoundary.js
Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { console.log('---ErrorBoundary---'); super(props) this.state = { hasError: false } } componentDidCatch(error, info) { this.setState({ hasError: true }) } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>{'Something went wrong.'}</h1> } return this.props.children } } export default ErrorBoundary; |
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
import React from 'react'; import './App.css'; import ErrorBoundary from './ErrorBoundary'; class Item extends React.Component { constructor(props) { super(props); } render() { const {name} = this.props; if (name!== '1345577') { throw new Error("ERROR"); } return ( <div className="form-group"> <label className="col-xs-4 control-label">{name}</label> <div className="col-xs-8"> <input type='text' className='form-control' /> </div> </div> ); } } class App extends React.Component { constructor() { super(); this.state = { // array of objects // each object has property name, id list: [] }; this.addItem = this.addItem.bind(this); } //prototype methods run in strict mode. addItem() { const id = new Date().getTime().toString(); this.setState({ list: [ {name: id, id} , ...this.state.list] //list: [...this.state.list, {name: id, id} ] }); } render() { const { list } = this.state; return ( <div className="App"> <ErrorBoundary> <button className='btn btn-primary' onClick={this.addItem}> <b>Add item</b> to the beginning of the list </button> <h3>Better <code>key=id</code></h3> <form className="form-horizontal"> {this.state.list.map((todo) => <Item {...todo} key={todo.id} /> )} </form> </ErrorBoundary> </div> ); } } export default App; |