[React] Avoid this Common Suspense Gotcha in by Reading Data From Components
React in Data from by this Common Components
2023-09-14 08:59:14 时间
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> ); }
相关文章
- React核心原理与虚拟DOM
- React v18.x 在 react-router v6 使用 lazy 动态加载组件实现
- React中定义组件
- React面试:谈谈虚拟DOM,Diff算法与Key机制
- React源码分析3-render阶段(穿插scheduler和reconciler)
- React高级特性之Context
- 深度剖析React懒加载原理_2023-03-01
- React源码分析之render阶段
- React-Hooks源码解读
- React路由传递params、search、state参数的相关处理
- 前端框架_React知识点精讲
- Facebook:我们是如何构建第一个跨平台的 React Native APP
- 用法Oracle IN 用法简介(oracle的in)
- 如何在MySQL中代替IN关键字(mysql中代替in)
- MySQL中的IN语句是否能够走索引(mysql中in走索引么)
- MySQL中使用IN函数的查询限制是什么(mysql中in的限制)
- MySQL中IN的用法和意义(mysql中in的意思)
- MySQL中使用IN子句出现重复值问题的解决方法(mysql中in有重复值)
- MySQL中如何使用IN操作符(mysql中in怎么写)
- MySQL中为什么不能使用IN子查询(mysql不能in子查询)