当前位置: 首页 > news >正文

React16源码: React中的IndeterminateComponent的源码实现

IndeterminateComponent


1 )概述

  • 这是一个比较特殊的component的类型, 就是还没有被指定类型的component
  • 在一个fibrer被创建的时候,它的tag可能会是 IndeterminateComponent
  • 在 packages/react-reconciler/src/ReactFiber.js 中,有一个方法
  • createFiberFromTypeAndProps 中,一开始就声明了
    let fiberTag = IndeterminateComponent;
    let resolvedType = type;
    // 一开始
    if (typeof type === 'function') {// 在 function 下只是判断了 constructor是否存在// 在不存在的时候,是否认为它是一个 FunctionComponent 呢,实际上并没有// 实际上我们写的任何一个 function component 一开始就是 IndeterminateComponent 类型if (shouldConstruct(type)) {// 存在,则赋值为 ClassComponentfiberTag = ClassComponent;}
    } else if (typeof type === 'string') {fiberTag = HostComponent;
    } else {// 省略
    }
    
  • 在最终调用 createFiber 创建 Fiber 对象

2 )源码

定位到 packages/react-reconciler/src/ReactFiber.js
进入 mountIndeterminateComponent 方法

// 
function mountIndeterminateComponent(_current,workInProgress,Component,renderExpirationTime,
) {// 首先判断 _current 是否存在,存在则进行初始化操作// 因为只有在第一次渲染的时候,才有 indeterminate component 这种情况// 经过第一次渲染之后,我们就会发现 indeterminate component 的具体的类型// 这种情况,可能是中途抛出一个 error 或 promise 等情况,比如 Suspense 组件// 这时候初始化是为了 去除 _current 和 workInProgress 相关联系,因为需要重新进行初次渲染的流程if (_current !== null) {// An indeterminate component only mounts if it suspended inside a non-// concurrent tree, in an inconsistent state. We want to treat it like// a new mount, even though an empty version of it already committed.// Disconnect the alternate pointers._current.alternate = null;workInProgress.alternate = null;// Since this is conceptually a new fiber, schedule a Placement effectworkInProgress.effectTag |= Placement;}const props = workInProgress.pendingProps;const unmaskedContext = getUnmaskedContext(workInProgress, Component, false);const context = getMaskedContext(workInProgress, unmaskedContext);prepareToReadContext(workInProgress, renderExpirationTime);prepareToUseHooks(null, workInProgress, renderExpirationTime);let value;if (__DEV__) {if (Component.prototype &&typeof Component.prototype.render === 'function') {const componentName = getComponentName(Component) || 'Unknown';if (!didWarnAboutBadClass[componentName]) {warningWithoutStack(false,"The <%s /> component appears to have a render method, but doesn't extend React.Component. " +'This is likely to cause errors. Change %s to extend React.Component instead.',componentName,componentName,);didWarnAboutBadClass[componentName] = true;}}if (workInProgress.mode & StrictMode) {ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);}ReactCurrentOwner.current = workInProgress;value = Component(props, context); } else {value = Component(props, context); // 调用 Component 方法}// React DevTools reads this flag.workInProgress.effectTag |= PerformedWork;// 符合这个条件,认为是 ClassComponent, 具有 render 方法if (typeof value === 'object' &&value !== null &&typeof value.render === 'function' &&value.$$typeof === undefined) {// Proceed under the assumption that this is a class instanceworkInProgress.tag = ClassComponent; // 这里认为它是一个 ClassComponent// Throw out any hooks that were used.resetHooks();// Push context providers early to prevent context stack mismatches.// During mounting we don't know the child context yet as the instance doesn't exist.// We will invalidate the child context in finishClassComponent() right after rendering.let hasContext = false;if (isLegacyContextProvider(Component)) {hasContext = true;pushLegacyContextProvider(workInProgress);} else {hasContext = false;}workInProgress.memoizedState =value.state !== null && value.state !== undefined ? value.state : null;const getDerivedStateFromProps = Component.getDerivedStateFromProps;if (typeof getDerivedStateFromProps === 'function') {applyDerivedStateFromProps(workInProgress,Component,getDerivedStateFromProps,props,);}adoptClassInstance(workInProgress, value);mountClassInstance(workInProgress, Component, props, renderExpirationTime);return finishClassComponent(null,workInProgress,Component,true,hasContext,renderExpirationTime,);} else {// 否则按照 FunctionComponent 来渲染// Proceed under the assumption that this is a function componentworkInProgress.tag = FunctionComponent; value = finishHooks(Component, props, value, context);if (__DEV__) {if (Component) {warningWithoutStack(!Component.childContextTypes,'%s(...): childContextTypes cannot be defined on a function component.',Component.displayName || Component.name || 'Component',);}if (workInProgress.ref !== null) {let info = '';const ownerName = ReactCurrentFiber.getCurrentFiberOwnerNameInDevOrNull();if (ownerName) {info += '\n\nCheck the render method of `' + ownerName + '`.';}let warningKey = ownerName || workInProgress._debugID || '';const debugSource = workInProgress._debugSource;if (debugSource) {warningKey = debugSource.fileName + ':' + debugSource.lineNumber;}if (!didWarnAboutFunctionRefs[warningKey]) {didWarnAboutFunctionRefs[warningKey] = true;warning(false,'Function components cannot be given refs. ' +'Attempts to access this ref will fail.%s',info,);}}if (typeof Component.getDerivedStateFromProps === 'function') {const componentName = getComponentName(Component) || 'Unknown';if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {warningWithoutStack(false,'%s: Function components do not support getDerivedStateFromProps.',componentName,);didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;}}if (typeof Component.contextType === 'object' &&Component.contextType !== null) {const componentName = getComponentName(Component) || 'Unknown';if (!didWarnAboutContextTypeOnFunctionComponent[componentName]) {warningWithoutStack(false,'%s: Function components do not support contextType.',componentName,);didWarnAboutContextTypeOnFunctionComponent[componentName] = true;}}}reconcileChildren(null, workInProgress, value, renderExpirationTime);return workInProgress.child;}
}
  • 基于上述判断条件 能认定是一个 ClassComponent,后续渲染一定会按照 ClassComponent 进行
    • if ( typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined ){}
  • 现在来测试一下,看下 function component 是否可以执行
    import React from 'react'export default function TestIndeterminationComponent() {return {componentDidMount() {console.log('invoker')},render() {return <span>aaa</span>}}
    }
    
    • 上述都能正常显示,以及打印 console 输出
    • 也就是说,对于一个 function component, 如果里面 return 的对象,具有 render 方法
    • 就认为它是一个 class component 一样的类型,去使用它
    • 并且在里面声明的生命周期方法都会被它调用
    • 这是 IndeterminateComponent 的特性
  • 在最初我们渲染的时候,所有的 function component 都是 IndeterminateComponent 的类型
  • 在第一次渲染之后,我们根据渲染类型的返回,最终得到具体类型
  • 可以通过 function component 返回一个对象的方式去渲染一个类似 classComponent 这样的类型
  • 注意,一般不推荐这么写

相关文章:

React16源码: React中的IndeterminateComponent的源码实现

IndeterminateComponent 1 &#xff09;概述 这是一个比较特殊的component的类型&#xff0c; 就是还没有被指定类型的component在一个fibrer被创建的时候&#xff0c;它的tag可能会是 IndeterminateComponent在 packages/react-reconciler/src/ReactFiber.js 中&#xff0c;有…...

SpringBoot:详解Bean生命周期和作用域

&#x1f3e1;浩泽学编程&#xff1a;个人主页 &#x1f525; 推荐专栏&#xff1a;《深入浅出SpringBoot》《java项目分享》 《RabbitMQ》《Spring》《SpringMVC》 &#x1f6f8;学无止境&#xff0c;不骄不躁&#xff0c;知行合一 文章目录 前言一、生命周期二…...

【图解数据结构】顺序表实战指南:手把手教你详细实现(超详细解析)

&#x1f308;个人主页&#xff1a;聆风吟 &#x1f525;系列专栏&#xff1a;图解数据结构、算法模板 &#x1f516;少年有梦不应止于心动&#xff0c;更要付诸行动。 文章目录 一. ⛳️线性表1.1 &#x1f514;线性表的定义1.2 &#x1f514;线性表的存储结构 二. ⛳️顺序表…...

WordPress怎么禁用文章和页面古腾堡块编辑器?如何恢复经典小工具?

现在下载WordPress最新版来搭建网站&#xff0c;默认的文章和页面编辑器&#xff0c;以及小工具都是使用古腾堡编辑器&#xff08;Gutenberg块编辑器&#xff09;。虽然有很多站长说这个编辑器很好用&#xff0c;但是仍然有很多站长用不习惯&#xff0c;觉得操作太难了&#xf…...

【HarmonyOS】掌握布局组件,提升应用体验

从今天开始&#xff0c;博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”&#xff0c;对于刚接触这项技术的小伙伴在学习鸿蒙开发之前&#xff0c;有必要先了解一下鸿蒙&#xff0c;从你的角度来讲&#xff0c;你认为什么是鸿蒙呢&#xff1f;它出现的意义又是…...

第4周:Pytorch——综合应用和实战项目 Day 28-30: 学习资源和社区参与

第4周&#xff1a;综合应用和实战项目 Day 28-30: 学习资源和社区参与 在这个阶段&#xff0c;我们将探索更多的学习资源并鼓励参与PyTorch和TensorFlow的社区&#xff0c;以进一步提升技术和融入开发者社群。 学习资源&#xff1a; 论文&#xff1a;阅读最新的机器学习和深度…...

TypeScript教程(一)在vscode中的配置TypeScript环境

TypeScript教程&#xff08;一&#xff09;在vscode中的配置TypeScript环境 文章目录 TypeScript教程&#xff08;一&#xff09;在vscode中的配置TypeScript环境一、前言二、具体步骤1、Node.js安装2、TypeScript安装3、helloworld 一、前言 未来的开发者们请上座&#xff0c…...

sshpass的安装与使用

一.简介 1.定义&#xff1a; ssh 登陆不能在命令行中指定密码&#xff0c;sshpass 的出现则解决了这一问题。它允许你用 -p 参数指定明文密码&#xff0c;然后直接登录远程服务器&#xff0c;它支持密码从命令行、文件、环境变量中读取。 2.使用 sshpass 原因 使用 sshpass…...

Excel·VBA合并工作簿2

其他合并工作簿的方法&#xff0c;见之前的文章《ExcelVBA合并工作簿》 目录 8&#xff0c;合并文件夹下所有工作簿中所有工作表&#xff0c;按表头汇总举例 8&#xff0c;合并文件夹下所有工作簿中所有工作表&#xff0c;按表头汇总 与之前的文章《ExcelVBA合并工作簿&#x…...

linux内核原理--分页,页表,内核线性地址空间,伙伴系统,内核不连续页框分配,内核态小块内存分配器

1.分页&#xff0c;页表 linux启动阶段&#xff0c;最初运行于实模式&#xff0c;此阶段利用段寄存器&#xff0c;段内偏移&#xff0c;计算得到物理地址直接访问物理内存。 内核启动后期会切换到保护模式&#xff0c;此阶段会开启分页机制。一旦开启分页机制后&#xff0c;内…...

【MongoDB】下载安装、指令操作

目录 1.下载安装 2.指令 2.1.基础操作指令 2.2.增加 2.3.查询 2.4.修改 2.5.删除 前言&#xff1a; 关于MongoDB的核心概念请移步&#xff1a; 【文档数据库】ES和MongoDB的对比-CSDN博客 1.下载安装 本文以安装Windows版本的mongodb为例&#xff0c;Linux版本的其实…...

k8s-pvc/pv扩容记录

背景 一次聊天过程中&#xff0c;对方提及pvc的扩容&#xff0c;虽然有注意过 storageclass 有个AllowVolumeExpansion的配置&#xff08;有些csi插件是不支持该配置的&#xff0c;比如local-volume-provisoner&#xff09;&#xff0c;但是没有实际用过&#xff0c;所以还是心…...

关于Unity插件TriLib使用的一点儿心得

最近做一个项目的时候&#xff0c;由于要求动态加载fbx或者glb等格式文件&#xff0c;而我们自己开发加载插件难度又有点大&#xff0c;所以最后使用了TriLib这个插件&#xff0c;现在说一点使用心得。 由于文件加载之后要对加载的内容进行复制&#xff0c;比如加载一个柱子&am…...

计算机二级Python基本排序题-序号45(补充)

1. 文件"singup.txt”中保存了若干条参加运动会学生的报名记录&#xff0c;每条记录的形式为“班级号_学号”&#xff0c;例如"A1_12”&#xff0c;将每个班级报名情按参加运动会人数从多到少排列&#xff08;假设不存在人数相同的情况&#xff09;并输出&#xff0c…...

响应式Web开发项目教程(HTML5+CSS3+Bootstrap)第2版 例4-6 fieldset

代码 <!doctype html> <html> <head> <meta charset"utf-8"> <title>fieldset</title> </head><body> <form action"#"><fieldset><legend>学生信息</legend>姓名&#xff1a;&…...

html渲染优先级

在前端开发中&#xff0c;优先布局是指在设计和构建页面时&#xff0c;将页面的各个部分按照其重要性和优先级进行排序&#xff0c;并依次进行布局和开发。这种方法可以帮助开发团队在项目初期就确定页面结构的核心部分&#xff0c;从而更好地掌控项目的整体进度和优先级。且确…...

linux 更新镜像源

打开终端&#xff0c;备份一下旧的 源 文件&#xff0c;以防万一 cd /etc/apt/ ls sudo cp sources.list sources.list.bak ls然后打开清华大学开源软件镜像站 搜索一下你的linux发行版本&#xff0c;我这里是ubuntu发行版本 点击这个上面图中的问号 查看一下自己的版本号&a…...

【征服Redis12】redis的主从复制问题

从现在开始&#xff0c;我们来讨论redis集群的问题&#xff0c;在前面我们介绍了RDB和AOF两种同步机制&#xff0c;那你是否考虑过这两个机制有什么用呢&#xff1f;其中的一个重要作用就是为了集群同步设计的。 Redis是一个高性能的键值存储系统&#xff0c;广泛应用于Web应用…...

php函数 一

一 自动加载 1.1 __autoload(string $class) 类自动加载&#xff0c;7.2版本之后废弃。可使用sql_autoload_register()注册方法实现。 类自动加载&#xff0c;无返回值。 #php7.2之前function __autoload($class) {if(strpos($class, CI_) ! 0){if (file_exists(APPPATH . …...

监督学习 - 梯度提升回归(Gradient Boosting Regression)

什么是机器学习 梯度提升回归&#xff08;Gradient Boosting Regression&#xff09;是一种集成学习方法&#xff0c;用于解决回归问题。它通过迭代地训练一系列弱学习器&#xff08;通常是决策树&#xff09;来逐步提升模型的性能。梯度提升回归的基本思想是通过拟合前一轮模…...

KubeSphere 容器平台高可用:环境搭建与可视化操作指南

Linux_k8s篇 欢迎来到Linux的世界&#xff0c;看笔记好好学多敲多打&#xff0c;每个人都是大神&#xff01; 题目&#xff1a;KubeSphere 容器平台高可用&#xff1a;环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

【决胜公务员考试】求职OMG——见面课测验1

2025最新版&#xff01;&#xff01;&#xff01;6.8截至答题&#xff0c;大家注意呀&#xff01; 博主码字不易点个关注吧,祝期末顺利~~ 1.单选题(2分) 下列说法错误的是:&#xff08; B &#xff09; A.选调生属于公务员系统 B.公务员属于事业编 C.选调生有基层锻炼的要求 D…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现录音机应用

1. 项目配置与权限设置 1.1 配置module.json5 {"module": {"requestPermissions": [{"name": "ohos.permission.MICROPHONE","reason": "录音需要麦克风权限"},{"name": "ohos.permission.WRITE…...

【无标题】湖北理元理律师事务所:债务优化中的生活保障与法律平衡之道

文/法律实务观察组 在债务重组领域&#xff0c;专业机构的核心价值不仅在于减轻债务数字&#xff0c;更在于帮助债务人在履行义务的同时维持基本生活尊严。湖北理元理律师事务所的服务实践表明&#xff0c;合法债务优化需同步实现三重平衡&#xff1a; 法律刚性&#xff08;债…...

Java数组Arrays操作全攻略

Arrays类的概述 Java中的Arrays类位于java.util包中&#xff0c;提供了一系列静态方法用于操作数组&#xff08;如排序、搜索、填充、比较等&#xff09;。这些方法适用于基本类型数组和对象数组。 常用成员方法及代码示例 排序&#xff08;sort&#xff09; 对数组进行升序…...

Java多线程实现之Runnable接口深度解析

Java多线程实现之Runnable接口深度解析 一、Runnable接口概述1.1 接口定义1.2 与Thread类的关系1.3 使用Runnable接口的优势 二、Runnable接口的基本实现方式2.1 传统方式实现Runnable接口2.2 使用匿名内部类实现Runnable接口2.3 使用Lambda表达式实现Runnable接口 三、Runnabl…...

stm32进入Infinite_Loop原因(因为有系统中断函数未自定义实现)

这是系统中断服务程序的默认处理汇编函数&#xff0c;如果我们没有定义实现某个中断函数&#xff0c;那么当stm32产生了该中断时&#xff0c;就会默认跑这里来了&#xff0c;所以我们打开了什么中断&#xff0c;一定要记得实现对应的系统中断函数&#xff0c;否则会进来一直循环…...

PLC入门【4】基本指令2(SET RST)

04 基本指令2 PLC编程第四课基本指令(2) 1、运用上接课所学的基本指令完成个简单的实例编程。 2、学习SET--置位指令 3、RST--复位指令 打开软件(FX-TRN-BEG-C)&#xff0c;从 文件 - 主画面&#xff0c;“B: 让我们学习基本的”- “B-3.控制优先程序”。 点击“梯形图编辑”…...

多模态大语言模型arxiv论文略读(112)

Assessing Modality Bias in Video Question Answering Benchmarks with Multimodal Large Language Models ➡️ 论文标题&#xff1a;Assessing Modality Bias in Video Question Answering Benchmarks with Multimodal Large Language Models ➡️ 论文作者&#xff1a;Jea…...