zoukankan      html  css  js  c++  java
  • [React] Avoid this Common Suspense Gotcha in by Reading Data From Components

    Suspense can have an unfriendly learning curve.
    Components with suspended content need a component boundary.
    Resource reads can't happen in the same component as the Suspense and error boundaries components.

    When you have your Suspense and error boundary components in place but still get errors about them absence, you probably need to move a read() call into a component.

    Problem Code:

    import React from "react";
    import ErrorBoundary from "./error-boundary";
    import { DelaySpinner } from "./ui";
    import { fetchPokemon, suspensify } from "./api";
    
    const PokemonDetail = React.lazy(() => import("./pokemon-detail"));
    
    let initialPokemon = suspensify(fetchPokemon(1));
    let initialCollection = suspensify(fetchPokemon(""));
    
    render() {
     return (
       <div>
        .
        .
        .
    
          <ErrorBoundary fallback="Couldn't cath 'em all.">
            <React.Suspense fallback="Loading pokemon...">
              {initialCollection.read().length}
            <React.Suspense>
          <ErrorBoundary>
        </div>
      );
    
    }

    I can tell you from experience, when you see these errors together and in particular, when you see the one that says, "Visit this URL to learn more about error boundaries," chances are you're trying to call read outside of a component. Whenever we call read, we need to do it inside of a component boundary.

    Fix:

    return (
      <div>
        .
        .
        .
    
        <ErrorBoundary fallback="Couldn't cath 'em all.">
          <React.Suspense fallback="Loading pokemon...">
            <PokemonCollection />
          <React.Suspense>
        <ErrorBoundary>
      </div>
    );
    function PokemonCollection() {
      return (
        <div>
          {initialCollection.read().results.map(pokemon => (
            <li>{pokemon.name}</li>
          ))}
        </div>
      );
    }
  • 相关阅读:
    Example of Formalising a Grammar for use with Lex & Yacc
    TCL脚本语言基础介绍
    linux环境下的c++编程
    如何利用FPGA进行时序分析设计
    可移植的配置visual studio工程第三方库
    [转]windows10 1703 鼠标右键打开命令提示符cmd
    重载和const形参的学习心得
    华为codecraft2018总结
    【转】C/C++使用心得:enum与int的相互转换
    C++学习笔记1-使用数组进行vector初始化
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12764987.html
Copyright © 2011-2022 走看看