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

本文主要是介绍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的源码实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/628452

相关文章

Nginx实现高并发的项目实践

《Nginx实现高并发的项目实践》本文主要介绍了Nginx实现高并发的项目实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录使用最新稳定版本的Nginx合理配置工作进程(workers)配置工作进程连接数(worker_co

python中列表list切分的实现

《python中列表list切分的实现》列表是Python中最常用的数据结构之一,经常需要对列表进行切分操作,本文主要介绍了python中列表list切分的实现,文中通过示例代码介绍的非常详细,对大家... 目录一、列表切片的基本用法1.1 基本切片操作1.2 切片的负索引1.3 切片的省略二、列表切分的高

基于Python实现一个PDF特殊字体提取工具

《基于Python实现一个PDF特殊字体提取工具》在PDF文档处理场景中,我们常常需要针对特定格式的文本内容进行提取分析,本文介绍的PDF特殊字体提取器是一款基于Python开发的桌面应用程序感兴趣的... 目录一、应用背景与功能概述二、技术架构与核心组件2.1 技术选型2.2 系统架构三、核心功能实现解析

使用Python实现表格字段智能去重

《使用Python实现表格字段智能去重》在数据分析和处理过程中,数据清洗是一个至关重要的步骤,其中字段去重是一个常见且关键的任务,下面我们看看如何使用Python进行表格字段智能去重吧... 目录一、引言二、数据重复问题的常见场景与影响三、python在数据清洗中的优势四、基于Python的表格字段智能去重

Spring AI集成DeepSeek实现流式输出的操作方法

《SpringAI集成DeepSeek实现流式输出的操作方法》本文介绍了如何在SpringBoot中使用Sse(Server-SentEvents)技术实现流式输出,后端使用SpringMVC中的S... 目录一、后端代码二、前端代码三、运行项目小天有话说题外话参考资料前面一篇文章我们实现了《Spring

Nginx中location实现多条件匹配的方法详解

《Nginx中location实现多条件匹配的方法详解》在Nginx中,location指令用于匹配请求的URI,虽然location本身是基于单一匹配规则的,但可以通过多种方式实现多个条件的匹配逻辑... 目录1. 概述2. 实现多条件匹配的方式2.1 使用多个 location 块2.2 使用正则表达式

使用Apache POI在Java中实现Excel单元格的合并

《使用ApachePOI在Java中实现Excel单元格的合并》在日常工作中,Excel是一个不可或缺的工具,尤其是在处理大量数据时,本文将介绍如何使用ApachePOI库在Java中实现Excel... 目录工具类介绍工具类代码调用示例依赖配置总结在日常工作中,Excel 是一个不可或缺的工http://

SpringBoot实现导出复杂对象到Excel文件

《SpringBoot实现导出复杂对象到Excel文件》这篇文章主要为大家详细介绍了如何使用Hutool和EasyExcel两种方式来实现在SpringBoot项目中导出复杂对象到Excel文件,需要... 在Spring Boot项目中导出复杂对象到Excel文件,可以利用Hutool或EasyExcel

前端bug调试的方法技巧及常见错误

《前端bug调试的方法技巧及常见错误》:本文主要介绍编程中常见的报错和Bug,以及调试的重要性,调试的基本流程是通过缩小范围来定位问题,并给出了推测法、删除代码法、console调试和debugg... 目录调试基本流程调试方法排查bug的两大技巧如何看控制台报错前端常见错误取值调用报错资源引入错误解析错误

Python如何实现读取csv文件时忽略文件的编码格式

《Python如何实现读取csv文件时忽略文件的编码格式》我们再日常读取csv文件的时候经常会发现csv文件的格式有多种,所以这篇文章为大家介绍了Python如何实现读取csv文件时忽略文件的编码格式... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍我们再日常读取csv文件的时候经常