navigation

[react] Hooks

[Encapsulation 01- Design Pattern] Design principles and factory pattern (simple abstract approach) Adapter pattern Decorator pattern [Encapsulation 02- Design Pattern] Command pattern Enjoy pattern Composite pattern Agent pattern

[React from zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose Deploy React + Egg +nginx+mysql [React From zero practice 05- background] Gitlab-CI using Docker automated deployment

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend

Vue. NextTick and VM.$nextTick ReactDOM. Render01

[Deployment 01] Nginx [Deployment 02] Docker deployVue project [Deployment 03] gitlab-CI

[Data Structures and Algorithms 01] Binary search and sort

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise Data Structures and Algorithms – Binary Search and Sorting Js and V8 Garbage collection mechanism [Deep 23] JS Design Patterns – Agents, strategies, singletons [Deep 24] Fiber

/ front-end learn java01 – SpringBoot combat environment configuration and the HelloWorld service [front-end learn java02 – SpringBoot combat] mybatis + mysql implementation song to add and delete [front-end learn java03 – SpringBoot combat] Lombok, log, Java04 -SpringBoot combat deployment [front-end science Java04 -SpringBoot combat] static resources + interceptor + front and back end file upload [front-end science Java05 -SpringBoot combat] common annotates + Redis implementation statistics function [front-end science Java06 -SpringBoot combat] inject + Swagger2 3.0 + unit test JUnit5 [Front-End science Java07 -SpringBoot real World] IOC scanner + transaction + Jackson [front-end science Java08 -SpringBoot real world summary 1-7 [java09-SpringBoot] Multi-module configuration + Mybatis-plus + single multi-module package deployment [Java10 -SpringBoot] Bean assignment conversion + parameter verification + global exception handling [java11-spring Security] configuration + memory + database = three ways to achieve RBAC [java12-spring Security] JWT [java13-SpringCloud] Eureka + RestTemplate + Zuul + Ribbon

(1) Pre-knowledge

(1) Some words

Update batched Internal // key._reactinternals reserved field Immutable // immutable // immutable // immutable // immutable // an immutable object with a single value condition // Freeze. Freeze cannot be added or deleted. // Freeze. Alter legacy blocking concurrent // blocking concurrent reuse Pure shallow // shallowEqual flush process weak // WeakMap passive passiveCopy the code

(2) React new and old life cycle comparison

  • Old life cycle

  • New life cycle

  • New life cycle
    • 1. RepealedcomponentWillMount componentWillReceiveProps componentWillUpdate
    • 2. AddedGetDerivedStateFromProps and getSnapshotBeforeUpateTo replace the three lifecycles above. Note: The old and new lifecycles above 1 and 2 cannot be mixed
    • 3. Added a few less commonly used life cyclescomponentDidCatch, getDerivedStateFromError

(3) PureComponent and React. Memo and shouldComponentUpdate

  • PureComponent
    • Only for class components
    • Shallow compared the props and state values before and after, shallow comparison (= = =)
    • If (equal return false, do not re-render) (not equal return true, re-render)
  • React.memo
    • React.memo(functionComponent, areEqual)
    • function areEqual(prevProps, nextProps) {}
    • Only for functional components
    • Props = props = props = props = props
    • If (equal returns true, no re-render) (unequal returns false, re-render)
  • shouldComponentUpdate
    • shouldComponentUpdate(nextProps, nextState)
    • Return true to rerender, false to not rerender

(4) the Object. The seal () and Object. The freeze ()

  • Objext.seal()
    • (seals) an object, (prevents new attributes from being added), and marks all existing attributes as (non-configurable – that is, cannot be deleted), and the value of the current attribute as long as it is writable.
    • In short 🙁Properties cannot be added/removed, but they can be modified )
    • Parameter: The object to be sealed
    • Return value: sealed object
    • Seal means to seal
  • Object.freeze()
    • (frozen) object, cannot (Add, modify, delete) object
    • Parameter: The object to be sealed
    • Return value: sealed object
Object.seal() --- const obj = {name: 'woow_wu7'} const obj2 = Object.seal(obj) obj1 === obj2 // true delete obj.name // false delete obj2.name // -------- Obj2. name = 'wu7' // ------- can modify the existing property obj.age = 20 // ------------ obj and obj2 do not have the age property, cannot add the propertyCopy the code
Object.freeze() --- const obj = {name: 'woow_wu7'} const obj2 = object.freeze (obj) obj1 === obj2 // true delete obj.name // -------- false, Can't delete the obj. Mame = 'wu7' / / -- -- -- -- -- -- -- not modify obj. Age = 20 / / -- -- -- -- -- -- -- -- -- -- - can not addCopy the code

(5) How does React distinguish classComponent from functionComponent?

  • isReactComponent
    • Component.prototype.isReactComponent = {};
      • The isReactComponent property is mounted on the Prototype of the classComponent class
      • ClassComponent if isReactComponent exists
  • isPureReactComponent
    • Use to flag whether it is a pureComponent

(6) React source code in some concepts

  • React (three modes)
    • legacy
      • There are no plans to clear the current use of React, but the mode may not support new features in the future
      • ReactDOM.render(<App />, rootNode)
    • blocking
      • It is currently being tested as a transition to the Concurrent mode
      • ReactDOM.createBlockingRoot(rootNode).render(<App />)
      • Blocking blocking piece
    • concurrent
      • It is currently being tested and will be used as the default development mode for React, which will enable all new features
      • ReactDOM.createRoot(rootNode).render(<App />)
      • Concurrent concurrent
  • work
    • The various activities that must be performed in React Reconciliation are called work
    • (state update) (props update) (ref update)
  • WorkTagfiber.tag
    • Use this to describe the react element type, which is the type of the fiber object, i.e. (fiber.tag).
  • side effects
    • Work that cannot be completed in the Render phase is called Side Effects
    • For example, manually changing the DOM or performing data requests, subscriptions, and so on in the lifecycle,
  • effectTagfiber.effectTag
    • In addition to common effects such as Update, the fiber node provides a convenient mechanism to track effects.
    • Each fiber node has an effCT associated with it, which is encoded as the corresponding value of the effectTag field, which is called fiber.effectTag
  • Effect list
    • Effect list is a linked list structure composed of firstEffect, nextEffect and lastEffect
    • Focus on the following
      • At the end of the Render phase, an Effect list is generated
      • During the Commit phase, React will walk through the Effect list and check the Effect type of the fiber object. When it finds functions related to other types, it will call them
  • stateNode
    • A reference to a component, a DOM node, or another instance of the React element associated with the fiber node
    • In general, we can say that this property is used to hold the local state associated with a fiber
    • fiber.stateNode

(7) Performance. Now () and the Date, now ()

  • performance.now()
    • Return time from (time-origin) to (the time the current call has passed)
      • A DOMHighResTimeStamp accurate to the millisecond
      • DOMHighResTimeStamp is a double that stores a time value at the millisecond level
  • Date.now()
    • Return the number of milliseconds since the current time is 1970/1/1/00:00:00
    • Date.now() === +new Date() === new Date - 0
performance.now -- const t0 = window.performance.now(); // Start time doSomething(); const t1 = window.performance.now(); Console. log("doSomething function executed "+ (t1-t0) +" milliseconds.")Copy the code

Component and PureComponent

PureComponent (2.1)

  • concept
    • PureComponent = Component + shouldComponentUpdate(nextProps, nextState)
    • (old props) and (new state) are used in shouldComponentUpdate().
    • General use: class extends A React.Com ponent/React PureComponent {}
  • What is the(Shallow comparison)
    • Shallow comparisons are also called (equality by reference), that is, congruence (===)
const o1 = {a: 1} const o2 = {a: 1} const o3 = o2 const o4 = (obj) => { obj.b = 1; Return obj} o1 === o2 // false o3 === o2 // true, o4(o1) === o1 // trueCopy the code

PureComponent source (2.2)

  • isPureReactComponent
    • The isPureReactComponent= True property is added to Prototype as opposed to Component
    • File location:packages/react/src/ReactBaseClasses.js
function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; / / assignment of empty object enclosing updater = updater | | ReactNoopUpdateQueue; ReactNoopUpdateQueue // - is an object, With these properties {isMounted, enqueueForceUpdate, enqueueReplaceState, enqueueSetState } } const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy()); // 1 // new ComponentDummy() // function ComponentDummy() {} // ComponentDummy.prototype = Component.prototype; // There is no property on the prototype object (pureComponent instance). // prototype // -isreactComponent // -setState // -forceUpdate // -isreactComponent // -setState // -forceUpdate pureComponentPrototype.constructor = PureComponent; // make sure that prototype.constructor is modified to prevent reference errors // If you do not modify the prototype object, // Avoid an extra prototype jump for these methods. Object.assign(pureComponentPrototype, Component.prototype); / / merge attributes pureComponentPrototype isPureReactComponent = true; // 3 // isPureReactComponent is used to determine whether a PureComponent is a PureComponentCopy the code
  • checkShouldComponentUpdate
    • File location:packages/react-reconciler/src/ReactFiberClassComponent.old.js
    • CheckShouldComponentUpdate check whether need to update, the new and old props and old and the new state as a layer of money
function checkShouldComponentUpdate( workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext, ) { ... // PureComponent2 if (ctor.prototype && ctor.prototype.isPureReactComponent) { return ( ! shallowEqual(oldProps, newProps) || ! ShallowEqual (oldState, newState) // Props and state); }... }Copy the code

(三) createRef

(3.1) React. CreateRef () the source code

export function createRef(): RefObject { const refObject = { current: null }; If (__DEV__) {object.seal (refObject); // ---------- current property cannot be added or removed, only modified, in the development environment} return refObject; }Copy the code

(3.2) React.createref () use case

class TestCreateRef extends React.Component {
    inputRef = React.createRef();
    componentDidMount() { this.inputRef.current.focus() }
    render() {
        return <input type="text" ref={this.inputRef} />
    }
}
Copy the code

(4) ReactDOM. Render ()

(4.1) Build the React source debugging environment

Create a React project using the create-react-app. 2. Yarn Run eject Pop-up configuration 3. Cloning the react source git clone [email protected]: facebook/react. Git 4. Put the cloned packages folder into the created React project folder (SRC /REACT_SOURCE_CODE_ANALYSIS) 5. Modify alias in resolve in webpack.config.js to configure alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', // Allows for better profiling with ReactDevTools ... (isEnvProductionProfile && { 'react-dom$': 'react-dom/profiling', 'scheduler/tracing': 'scheduler/tracing-profiling', }), ... (modules. WebpackAliases | | {}), / / + 'react' to add the following code: path. Resolve (__dirname, '.. /src/REACT_SOURCE_CODE_ANALYSIS/packages/react'), 'react-dom': path.resolve(__dirname, '.. /src/REACT_SOURCE_CODE_ANALYSIS/packages/react-dom'), 'shared': path.resolve(__dirname, '.. /src/REACT_SOURCE_CODE_ANALYSIS/packages/shared'), 'react-reconciler': path.resolve(__dirname, '.. /src/REACT_SOURCE_CODE_ANALYSIS/packages/react-reconciler'), } 6. Config /env.js const stringified = {__DEV__: true, __PROFILE__: true, __UMD__: true, __EXPERIMENTAL__: true True, // and globals in.eslintrc.json correspond to 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {})}; 7. The react project root directory to create. Eslintrc. Json {" extends ":" the react - app ", "globals" : {" __DEV__ ": true," __PROFILE__ ": true," __UMD__ ": true, "__EXPERIMENTAL__": true, } } 8. Remove esLint checks from webpack.config.js //! disableESLintPlugin && // new ESLintPlugin({ // // Plugin options // extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'], // formatter: require.resolve('react-dev-utils/eslintFormatter'), // eslintPath: require.resolve('eslint'), // failOnError: ! (isEnvDevelopment && emitErrorsAsWarnings), // context: paths.appSrc, // cache: true, // cacheLocation: path.resolve( // paths.appNodeModules, // '.cache/.eslintcache' // ), // // ESLint class options // cwd: paths.appPath, // resolvePluginsRelativeTo: __dirname, // baseConfig: { // extends: [require.resolve('eslint-config-react-app/base')], // rules: { // ... (! hasJsxRuntime && { // 'react/react-in-jsx-scope': 'error', // }), // }, // }, // }), 9. The SRC/REACT_SOURCE_CODE_ANALYSIS/packages/react - the reconciler/SRC/ReactFiberHostConfig. / / js / / commented import invariant the from 'shared/invariant'; // invariant(false, 'This module must be shimmed by a specific renderer.'); / / / / add visit export * from. / forks/ReactFiberHostConfig. "dom"; 10. The SRC/REACT_SOURCE_CODE_ANALYSIS/packages/Shared/ReactSharedInternals. / / js / / commented import * as the React from 'React'; Import ReactSharedInternals from '.. /react/src/ReactSharedInternals'; // ReactSharedInternals // const ReactSharedInternals = // React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; export default ReactSharedInternals; 11. src/REACT_SOURCE_CODE_ANALYSIS/packages/shared/invariant.js export default function invariant(condition, format, a, B, c, d, e, f) {// add the following line if (condition) return; throw new Error( "Internal React error: invariant() is meant to be replaced at compile " + "time. There is no runtime version." ); // import react from 'react'; // import react from 'react'; // import ReactDOM from 'react-dom'; import * as React from 'react'; Import * as ReactDOM from 'react-dom'; import * as ReactDOM from 'react-dom'; import * as ReactDOM from 'react-dom'; {"version": "0.2.0", "configurations": [{"type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "url": "http://localhost:3000", "webRoot": "${workspaceFolder}" } ] }Copy the code

(4.2) Reactdom.render () Basics

  • ReactDOM.render(element, container[, callback])
    • role
      • First render: Render a React element in the provided Container and return a reference to that component (or null for stateless components)
      • Update: If the React element has previously been rendered in the Container, this will be performed on it and only changes the DOM if necessary to map the latest React element
      • If a third argument is provided, it indicates that the (callback function) will be executed after (the first rendering or update) is complete.
  • What is the element in the parameter?
    • Element is a react element
        1. The react component returns a react element. Components are made up of elements
        1. React elements can be created using react. CreateElement (type, config, children)
        1. The react element is essentially a javascript object
    • React. CreateElement (type, config, children) source code
      • React. CreateElemen source analysis – see previous article
  • Reactdom.render () is divided into (three stages)
    • Init Indicates the initialization phase
      • Mainly responsible for generating the basic entity objects of the Fiber tree, such as fiberRoot, rootFiber
    • Render phase
      • Responsible for creating, scheduling, and harmonizing the Fiber tree
    • The commit phase
      • Render the real DOM according to virtualDOM

(4.3) ReactDOM. Render () the source code

  • ReactDOM. Render returns legacyRenderSubtreeIntoContainer ()
// ----------------------------------------------------------------------------------------------------------- Reactdom.render (element, container[, callback]) // -1. Initial render: render a React element in the provided Container and return a reference to that component (or null for stateless components) // 2. Update: -- If the React element has previously been rendered in the Container, this will be performed on it, and only changes the DOM if necessary to map the latest React element // - 2. // -element // -element represents a React element. The React component consists of an element, which is essentially a javascript object. // -react. CreateElement (type, config, children) => ReactElement(type, key, ref, self, The source, ReactCurrentOwner. Current, props) = > element / / - element object with basic attributes: / / - Type, key, ref, props, _owner, $$typeof __store, __self, __source properties // -container // -properties, that is, properties on components or elements // -callback: An optional callback function that is executed after (rendering or update) is complete // -3. Return value / / - legacyRenderSubtreeIntoContainer / / - legacyRenderSubtreeIntoContainer (null, element, container, false, Export function render(element: React$element <any>, container: container, callback:? Function, ) { if (__DEV__) { console.error( 'ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot', ); // createRoot // -Reactdom. render is not supported in React 18, } invariant(isValidContainerLegacy(Container), // legitimate node 'Target Container is not a DOM element.', ); // export default function invariant(condition, format, a, b, c, d, e, f) { // throw new Error( // 'Internal React error: invariant() is meant to be replaced at compile ' + // 'time. There is no runtime version.', // ); // } if (__DEV__) { const isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; // 1 // isContainerMarkedAsRoot // export function isContainerMarkedAsRoot(node: Container): boolean { // return !! node[internalContainerInstanceKey]; // } // 2 // internalContainerInstanceKey // const internalContainerInstanceKey = '__reactContainer$' + randomKey; // 3 // randomKey // const randomKey = Math.random() // .toString(36) // .slice(2); if (isModernRoot) { console.error( 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)? ', // you are using reactdom.render () on the container previously passed to reactdom.createroot (), this is not supported, do you want to call root.render(element)?) ; }} / / 1 / / legacyRenderSubtreeIntoContainer () / / render () function return value eventually legacyRenderSubtreeIntoContainer () / / legacy: Legacy + render + subtree + into + container Container / / 2 / / react a total of three models / / legacy / / after blocking / / concurrent react18 default to concurrent mode return legacyRenderSubtreeIntoContainer ( Null, // parentComponent parent element, // Children Container, // Container false, // forceHydrate // callback ); }Copy the code
  • legacyRenderSubtreeIntoContainer
    • We have mainly done the following
      • Create fiberRoot and rootFiber and reference each other
      • Associated with continer and Rootfiber.current
      • Event correlation
      • updateContainer()
// ----------------------------------------------------------------------------------------------------------- LegacyRenderSubtreeIntoContainer / / [0] legacyRenderSubtreeIntoContainer first render init mount / / 1 / / / / - 1. First render - there is no (old virtual DOM node) // - 2. In the update phase, there are many things to consider, such as moving, updating, plug-ins, etc. // 2 // How to determine whether it is the first render? // - Render the first time without the old virtual DOM node, so you can judge by (root). (let root = container._reactrootContainer) // 2 // initialize reactdom.render () as follows legacyRenderSubtreeIntoContainer( null, element, container, false, callback, ); function legacyRenderSubtreeIntoContainer( parentComponent: ? React$Component<any, any>, // init => null children: ReactNodeList, // render the first argument element container: Container forceHydrate: Boolean, // server side render identifier, init => false callback:? Function () {if (__DEV__) {topLevelUpdateWarnings(Container); warnOnInvalidCallback(callback === undefined ? null : callback, 'render'); } let root = container._reactRootContainer; // 2. The _reactRootContainer property is declared on the container. // 3. Root = undefined // 4.container // -1 // -container // -container is the second argument passed to reactdom.render (), which is the container that JSX mount, Is real DOM / / - generated below fiberRoot, root = container. _reactRootContainer = legacyCreateRootFromDOMContainer (), // -container._reactRootContainer // -container._reactRootContainer // -react You can read _reactRootContainer by document.querySelector('#root')._reactrootContainer // - You can see: (FiberRootNode(containerInfo, Tag, Hydrate)) 3 / / / / - _internalRoot / / - container. _reactRootContainer _internalRoot corresponding to this (fiberRoot) / / - _internalRoot === fiberRoot) // - internal = internal // 5. Root = fiberRoot; The fiberRoot object is the root node of the fiber tree (each DOM node corresponds to a fiber object). Let fiberRoot: fiberRoot; // Cache old virtual DOM for comparison // fiberRoot // 1. // fiberRoot can have only one fiber node. // fiberRoot can have more than one fiber node. StateNode = fiberRoot // -fiberroot. Current = rootFiber // -fiberroot. Root) {/ / Initial mount / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- initialization phase of the mount, the Initial rendering, Root does not exist // Root does not exist on the first render, // container._reactRootContainer. // Container. _reactRootContainer FiberRoot // 2 // fiberRoot === fiberRootNode object // 3 // Review fiberRoot and rootFiber again // - fiberRoot // - fiberRoot -fiberroot. current === = rootFiber // -rootfiber. stateNode === = fiberRoot root = container._reactRootContainer = legacyCreateRootFromDOMContainer( container, forceHydrate, // init => false ); fiberRoot = root; If (typeof callback === 'function') { If const originalCallback = callback; callback = function() { const instance = getPublicRootInstance(fiberRoot); originalCallback.call(instance); }; } // Initial mount should not be batched. // Initial render is not batch update, Can guarantee (update efficiency and user experience) / / such as initial rendering hope faster speed for the user to see the UI flushSyncWithoutWarningIfAlreadyRendering (() = > {updateContainer (children, fiberRoot, parentComponent, callback); }); / / flushSyncWithoutWarningIfAlreadyRendering / / - function signature: flushSyncWithoutWarningIfAlreadyRendering(fn) => fn() } else { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- update phase fiberRoot = root; if (typeof callback === 'function') { const originalCallback = callback; callback = function() { const instance = getPublicRootInstance(fiberRoot); originalCallback.call(instance); }; } batched Update updateContainer(children, fiberRoot, parentComponent, callback); } return getPublicRootInstance(fiberRoot); }Copy the code
  • updateContainer()
    • Mainly responsible for
      • Get the lane priority of the current fiber node. The smaller the lane, the higher the priority
      • To create the context
      • Create an Update object and join the team
      • Schedule the rootFiber of the current node
// ----------------------------------------------------------------------------------------------------------- UpdateContainer // [1] updateContainer // updateContainer(children, fiberRoot, parentComponent, callback); // 1 // updateContainer Create an update object for the current fiber node based on the lane priority and queue it // 3. // 2 // call stack: render > legacyRenderSubtreeIntoContainer > updateContainer export function updateContainer( element: ReactNodeList, container: OpaqueRoot, // fiberRoot parentComponent: ? React$Component<any, any>, callback: ? Function, ): Lane { if (__DEV__) { onScheduleRoot(container, element); } const current = container.current; Container. Current = fiberRoot. Current = rootFiber; HostRoot const eventTime = requestEventTime(); // 541304.0999999642 const lane = requestUpdateLane(current); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Since the performance for the current page. The timing. NavigationStart between the current time and the number of milliseconds the if (enableSchedulingProfiler) {/ / export const enableSchedulingProfiler = __PROFILE__ && __EXPERIMENTAL__; markRenderScheduled(lane); } const context = getContextForSubtree(parentComponent); // mount => return an empty object if (container. Context === null) {// mount => The context on the container is empty Container. Context = context; // Give container.context = {}} else {container.pendingContext = context; } if (__DEV__) { if ( ReactCurrentFiberIsRendering && ReactCurrentFiberCurrent ! == null && ! didWarnAboutNestedUpdates ) { didWarnAboutNestedUpdates = true; console.error( 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(ReactCurrentFiberCurrent) || 'Unknown', ); } } const update = createUpdate(eventTime, lane); // Return update object with tag=0 and lane=1 // Caution: React DevTools currently depends on this property // being called "element". // Warning: React DevTools currently depends on this property named "element". update.payload = {element}; callback = callback === undefined ? null : callback; if (callback ! == null) { if (__DEV__) { if (typeof callback ! == 'function') { console.error( 'render(...) : Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback, ); } } update.callback = callback; } enqueueUpdate(current, update, lane); // enqueueUpdate // enqueueUpdate is used to add a sharedQueue, Const root = scheduleUpdateOnFiber(current, Lane, eventTime); If (root! == null) { entangleTransitions(root, current, lane); } return lane; // Return priority (current node is fiberRoot)}Copy the code

(five) source code analysis warehouse address

  • ReactDOM. Render – Source code analysis warehouse address
  • Reactdom.render – Mind map

data

  • React source code tutorial 1 juejin.cn/post/694268…
  • React to debug the source zhuanlan.zhihu.com/p/336933386 tutorial 2
  • Summary of concepts related to fiber tech.tuya.com/react-fiber…
  • EnqueueUpdate juejin. Cn/post / 695158…