zoukankan      html  css  js  c++  java
  • [React] Handle React Suspense Errors with an Error Boundary

    Error Boundaries are the way you handle errors with React, and Suspense embraces this completely. Let's take a look at how to handle asynchronous errors with Suspense and Error Boundaries.

    In previous post, we used React.Suspense with fallback (for loading..), in this post, we will see how to handle error case with ErrorBoundary. https://reactjs.org/docs/error-boundaries.html

    NPM module: https://npm.im/react-error-boundary

    An ErrorBoundary component:

    // utils.js
    
    class ErrorBoundary extends React.Component {
      state = {error: null}
      static getDerivedStateFromError(error) {
        return {error}
      }
      componentDidCatch() {
        // log the error to the server
      }
      tryAgain = () => this.setState({error: null})
      render() {
        return this.state.error ? (
          <div>
            There was an error. <button onClick={this.tryAgain}>try again</button>
            <pre style={{whiteSpace: 'normal'}}>{this.state.error.message}</pre>
          </div>
        ) : (
          this.props.children
        )
      }
    }

    ---

    import React from 'react'
    import fetchPokemon from '../fetch-pokemon'
    import {PokemonDataView, ErrorBoundary} from '../utils'
    
    let pokemon
    let pokemonError
    let pokemonPromise = fetchPokemon('pikachue').then(
      p => {
        console.log('promise resolve')
        pokemon = p
      },
      e => {
        pokemonError = e
      },
    )
    
    function PokemonInfo() {
      console.log('PokemonInfo init')
    
      if (pokemonError) {
        throw pokemonError
      }
    
      if (!pokemon) {
        throw pokemonPromise // this API might change
      }
    
      return (
        <div>
          <div className="pokemon-info__img-wrapper">
            <img src={pokemon.image} alt={pokemon.name} />
          </div>
          <PokemonDataView pokemon={pokemon} />
        </div>
      )
    }
    
    function App() {
      return (
        <div className="pokemon-info">
          <ErrorBoundary>
            <React.Suspense
              fallback={
                console.log('loading pokemon...') && <div>Loading pokemon...</div>
              }
            >
              <PokemonInfo />
            </React.Suspense>
          </ErrorBoundary>
        </div>
      )
    }
    
    export default App
  • 相关阅读:
    Java版本及历史简述
    ASCII、Unicode、UTF-8、UTF-16、GBK、GB2312、ANSI等编码方式简析
    同步(Synchronous)和异步(Asynchronous)方法的区别
    例10-12 *uva1637(概率dp)
    例10-11 uva11181
    例10-10 uva10491(简单概率)
    例10-9 uva1636简单概率问题
    全排列hash-康拓展开
    10-8 uva1262密码
    例10-6 uva1635(唯一分解定理)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12006526.html
Copyright © 2011-2022 走看看