☞Read the original

Some people may not understand, for whom is the war of big front-end platform ignited, why do we fight?

Focusing on the front end of the mobile Internet to get rich has always been our highest ideal, and ReactNative is the bridgehead in the middle.

Throughout the industry wind direction, there are those who sit on the sidelines, there are those who sharpen their knives, there are those who give up from entry, there are those who take bold measures, but lack of deep latent micro operation.

Aha, it’s time for me to do something.

Offering a”Big hna operation“, based on React Developer Tools after one year of unremitting researchResearch and development of the plugin, real-time rendering of three run-time trees —Fiber double tree,Native tree View,The React method calls the tree, under the guidance of God’s perspective and time travel, the Fiber algorithm breaks through the mysterious clouds and becomes a double dragon.

This paper mainly analyzes the ReactNative (RN) source code of React.js. First, it makes clear the API developers are exposed to, and then dig into the corresponding underlying implementation logic, and finally find the space for micro-operation. If you are not familiar with RN, you are advised to take a look at “Attack ReactNative- Swift as the Wind” to warm up. From the perspective of “principle + practice, learn and do by doing”, the article hand-writes The Stone Age RN with broad lines to describe cross-platform routines and outflank, which is relatively easy! This article is positive just React source code, slightly burn brain.

You know, to do great things, you have to use a big axe. First play Ali “three board axe” shake.

Set the target

Evangelism (Attack Methodology)

In recent years, the mobile Internet north drift career, give me a solid lesson: life, in addition to get rich, is to constantly explore, abstract, practice, strengthen their own methodology, stable their values, the process is spiraling up, as long as grasp the summary of the secret, growth is very happy.

The driving force behind my attack on RN was to use falsehood to fix the truth. Platform technology may eventually be the king of Flutter or small programs (there are still many people who are obsessed with which one is better and delay their study, in fact, it is just like tsinghua university or Peking University, is it so difficult to choose the Top2 universities, the really difficult choice is the Top3 universities), but it does not matter, I can give one, I will be able to reverse three, this is bullying. My goal is to reinforce a methodology for building RN skills from zero to a level of advanced Android proficiency that is equally applicable to Flutter and apts.

Teach (know algorithm)

Now the market high level of RN analysis articles are too few (foreigners write hardcore articles), and mostly stay in the theoretical level, only give algorithm theory and source code fragments, it is difficult to in-depth micro, can only say what the author is what, anyway unknown. Well, self-reliance gnaw source code must be on the agenda.

I always believe that only the source code is the only truth, not two notes, the spark of thought, king of pesticides.

In fact, finally in tears to understand and verify this point, source law well, much more than I wanted (poverty limited my imagination). To put it mildly, technology grows. To put it more broadly, core competence (money).

In this article, I’m going to share with you how to read code with relative ease through advanced productivity, rather than rigid, flowing English reading.

  1. Bearing on the(User mode – how to use the upper API)
    • What is the role of methods (constructor, setState, forceUpdate, Render) in a component?
    • What is the lifecycle call time?
    • Will parent and sibling components refresh when child components change? What’s the difference between the props and the state?
    • How is PureComponent better than Component, and how can it be better?
    • Best practices (JSX not creating temporary functions, Immutable, performance optimization)?
  2. Under the rev.(Kernel state – How to play the underlying principle)
    • What are the meanings of the various concepts, and what are the corresponding data structures?
    • Fiber Double tree algorithm?
    • Where’s the Diff algorithm?
    • Where do Native operation instructions come from?

Answer the question (quiz you)

Clever children boots often have some urgent need to personally operate the question, I can not escape the vulgar. The question is there. What is the satisfactory answer?

component

  1. There are only a few components, but when you use react-devTools you see a bunch of layouts, and Context.Consumer.
  2. The React component and Native View do not seem to correspond one to one. What is the mapping?
  3. When, what does it do, and best practices for component common API calls?
// Class Component<P, S> {// props; state; // method constructor(context); setState(state, callback): void; forceUpdate(callBack): void; render(): ReactNode; }Copy the code

The life cycle

  1. Distinguish which methods are called only once and which may be called multiple times? Which methods can use setState and which can’t?
  2. Distinguish each method call condition, is it props changed or state, initialized, updated or both?
  3. What are the methods for starting deprecation and additions in Act 16.3, and what are the fill strategies? Can discarded methods still be used now, and what about mixing old and new methods?
  4. When, what does it do, and best practices for component lifecycle API calls?
Interface StaticLifecycle {getDerivedStateFromProps? : GetDerivedStateFromProps; } // NewLifecycle interface NewLifecycle<P, S, SS> {getSnapshotBeforeUpdate? (prevProps, prevState): SS | null; componentDidUpdate? (prevProps, prevState, snapshot): void; } // interface DeprecatedLifecycle<P, S> {componentWillMount? (): void; UNSAFE_componentWillMount? (): void; componentWillReceiveProps? (nextProps, nextContext): void; UNSAFE_componentWillReceiveProps? (nextProps, nextContext): void; componentWillUpdate? (nextProps, nextState, nextContext): void; UNSAFE_componentWillUpdate? (nextProps, nextState, nextContext): void; } interface ComponentLifecycle<P, S, SS> extends NewLifecycle<P, S, SS>, DeprecatedLifecycle<P, S> { componentDidMount? (): void; shouldComponentUpdate? (nextProps, nextState, nextContext): boolean; componentWillUnmount? (): void; componentDidCatch? (error, errorInfo): void; }Copy the code

The data structure

  1. What are the different meanings of Element, Instance, DOM, Component, Fiber and their relationships?
  2. What are the attributes of Fiber node data structure?

Virtual DOM

  1. What fake problems does Virtual DOM encounter and what real ones do it solve?
  2. React has a DOM tree. How to operate the tree?

The Diff algorithm

  1. What are the strategies of the Diff algorithm, and what are the best practices that come out of it?
  2. React has a Tree Diff algorithm. Component Diff; Component Diff; Element Diff add, delete, and reuse keys), where are the codes, and how are they compared?

The principle of

  1. Where is React efficient? How did you do that?
  2. React workflow?
  3. How to associate Native custom components?
  4. What is Fiber double tree? Why are you so awesome?

After the process

learning

We are not alone in the fight (want to make a fortune), by no means behind closed doors, only by pooling wisdom, standing on the shoulders of giants can get twice the result with half the effort.

Online a keyword index, find some time, give some patience, extensive reading + intensive reading dozens of articles, your feeling can slowly drop up.

In line with the firm see more, the number of dead power pile, after uninterrupted reading output, posture saw rise, for example, through XMind free scaling source map to help understand, handwritten RN to seek theory and practice, abstract pseudo code statement help to clarify.

For hardcore goods, please check my blog homepage and wechat moments, and I will periodically summarize the excellent ReactNative articles I have seen. Send friend circle, I am serious, stop is impossible to stop, go to work every day send. Welcome to learn from each other and make progress together.

Fiber Architecture Milestone

**Why: ** is running too fast to process user responses, causing the interface to crack.

**What: **Fiber is a more sophisticated concurrency mechanism than thread control. Support update process fragmentation, break the whole into parts, allowing emergency tasks to jump the queue, can interrupt recovery. Essentially, it’s also a tool to help developers manipulate the DOM API to build pages.

**How Much: ** Enjoy the smooth.

Lin Clark — A Cartoon Intro to Fiber-React Conf 2017 Lin Clark — A Cartoon Intro to Fiber-React Conf 2017 This is so good, I suggest you take a look at it (no subtitles, if you are fluent in English, you can challenge it, or pretend to understand it with your cranky imagination like me). Most of the Fiber algorithm analysis on the Internet references her cartoons.

The term

Component: Small reusable code snippets that return React elements to render in the page. There are class components (normal components that inherit from Component and pure components that inherit from PureComponent) and functional components (functions that return Element directly).

Render () {return <Text style={{color: 'black'}}>{' 0'}</Text>; }}Copy the code
PureComponent {render() {return <Text style={{color: 'black'}}>{' 0'}</Text>; }}Copy the code
// Const App = function () {return <Text style={{color: 'black'}}>{' 0'}</Text>; }Copy the code

JSX: syntactic sugar for converting htML-like tagging to pure Element function call writing. Babel translates JSX into a function call called react. createElement.

Class App extends React.Component {render() {react.createElement (// type {$$typeof: Symbol(react. Forward_ref), displayName: "Text", propTypes: {... }, render: ƒ}, / / attribute props {style: {color: "black"}, __source: {... }, // children "click count 0"); }}Copy the code

Instance: component Instance, the result of the instantiation of the component class, ref points to the component Instance (functional components cannot be instantiated). New Component() is called when the Fiber node is generated.

// App {forceUpdate: ƒ (), isReactComponent: ƒ (), setState: ƒ (), componentDidMount: ƒ (), componentWillUnmount: ƒ (), constructor: ƒ App(props), isMounted: ƒ (), replaceState: , __proto__: Component }Copy the code

Element: An Element that describes what you want to see on the screen. Is a pure object description of a DOM node, that is, the virtual DOM, corresponding to the component render method mainly returns the value. See the React. The createElement method.

// React Element $$typeof: Symbol(React. Element), // props: {rootTag: 255}, // ref: null, // Type type: ƒ App(props), _owner: NULL, _store: {validated: true}, _self: null, _source: {fileName: "/ Users/shengshuqiang/dream/AdvanceOnReactNative/Aw... native/Libraries/ReactNative/renderApplication.js", lineNumber: 38}, __proto__: Object } // Text { $$typeof: Symbol(react. Element), key: null, props: {style: {color: "black"}, children: "0"}, ref: null, type: {$$typeof: Symbol(react. Forward_ref), displayName: "Text", propTypes: {... }, render: ƒ}, _owner: ƒ}, key: null, elementType: ƒ, type: ƒ,... }, _store: {validated: false}, _self: null, _source: {fileName: "/Users/shengshuqiang/dream/AdvanceOnReactNative/AwesomeProject/App.js", lineNumber: 213}, __proto__: Object }Copy the code

FiberNode: An operable fine-grained node in fragmentation update that stores intermediate calculation results and provides technical support for page refresh of “Emergency queue cutting and interrupted recovery”. See ReactNative createFiberFromElement.

// FiberNode {actualDuration: 175.7499999985157, actualStartTime: // Alternate tree, after render or setState is called, clones a mirror fiber, and diff changes are marked on the mirror fiber. Alternate: null, // first child: FiberNode {id: 12, tag: 11, key: Null, elementType: {... }, type: {... },... }, // TODO childExpirationTime: 0, contextDependencies: null, // Placement=2; Update=4; PlacementAndUpdate=6; Deletion=8; EffectTag: 5, // describes its corresponding component. For composite components, the type is a function or the class component itself. For host components (div, SPAN, and so on), the type is a string. Defines a function or class for this Fiber node. For class components, it points to constructors, and for DOM elements, it specifies HTML tags. I often use this field to understand which element the Fiber node is associated with. // ClassComponent corresponds to a function, such as APPContainer(). $$typeof: Symbol(react. Forward_ref), render: ƒ, displayName: "View"} HostComponent is a string, for example, RCTView. HostText corresponds to NULL. ElementType: ƒ App(props), // TODO expirationTime: 0, Id: 13, tag: 1, key: null, elementType: ƒ, type: ƒ, }, // I added the unique id of the Fiber node (with the id increment generated), used to generate the Fiber double tree ID: 11, index: 0, // reuse the identifier key: null, // refer to firstEffect lastEffect: FiberNode {id: 13, tag: 1, key: null, elementType: ƒ, type: ƒ,... }, // memoizedProps: {rootTag: 191}, // For creating the Fiber state of the output. MemoizedState: NULL, mode: 4, // workInProgress Tree each node has an Effect List to store the content that needs to be updated. Effect List nextEffect: FiberNode {id: 10, Tag: 5, Key: NULL, elementType: "RCTView", type: "RCTView",... }, // props is an argument to the function. A Fiber pendingProps is set at the beginning of execution and memoizedProps is set at the end. Props pendingProps: {rootTag: 191}, ref: null, // Parent node return: FiberNode {id: FiberNode} 10, tag: 5, key: null, elementType: "RCTView", type: "RCTView",... }, selfBasedConfiguration: 28.63000000070315, // Sibling: null, // Saves references to component class instances, DOM nodes, or other React element types associated with Fiber nodes. In general, we can think of this property as being used to preserve the local state associated with a Fiber node. HostRoot corresponds to {containerInfo}; ClassComponent corresponds to an instance of the function object new; HostComponent corresponding ReactNativeFiberHostComponent, contains _children and _nativeTag; HostText corresponds to nativeTag) stateNode: hookClazz {props: {... }, the context: {... }, refs: {... }, updater: {... }, _reactInternalFiber: FiberNode,... }, // It is used in the coordination algorithm to determine what needs to be done. As mentioned earlier, the work depends on the React elementType tag: 1, treeBaseDuration: 155.36499999871012, // same as elementType type type: ƒ App(props), // state update queue. Queues for status updates, callbacks, and DOM updates updateQueue: NULL, _debugID: 12, _debugIsCurrentlyTiming: false, _debugOwner: NULL, _debugSource: {fileName: "/ Users/shengshuqiang/dream/AdvanceOnReactNative/Aw... native/Libraries/ReactNative/renderApplication.js", lineNumber: 38}, __proto__: Object }Copy the code

DOM: Document Object Model, simply speaking, is the node of interface control tree (CORRESPONDING to Html is DOM tree, corresponding to Native is View tree).

Uimanager.createview [3,"RCTRawText",1,{"text":" clickthrough count "}] uimanager.createView [3,"RCTRawText",1,{"text":" clickthrough count "}] uimanager.createView [5,"RCTText",1,{"ellipsizeMode":"tail","allowFontScaling":true,"accessible":true,"color":-16777216}] UIManager.setChildren [5,[3]] UIManager.createView [7,"RCTView",1,{"flex":1,"pointerEvents":"box-none","collapsable":true}] UIManager.setChildren [7,[5]] UIManager.createView [9,"RCTView",1,{"pointerEvents":"box-none","flex":1}] UIManager.setChildren [9,[7]] UIManager.setChildren [1,[9]]Copy the code

Run (Playground)

Build your own playground — a native runnable environment (macOS, Android).

  1. Installation software: Webstorm (front-end development environment), AndroidStudio (Android development environment, Android simulator).
  2. Install dependencies: Install Xcode (iOS development environment, send iPhone emulator) and solve the problem.
  3. Use the React Native command line tool to create a new project called “AwesomeProject” :react-native init AwesomeProject.
  4. O,A simple Demo(A red button on the page that starts with 0 hits and switches to the “car” icon) test it out. The Demo is mainly used to observe the initial render and the user clicks render.

  5. See React Native Chinese Platform for more configuration details.

The source code

React, 0.59.8 React -native

  • RN’s top JS code is mainly implemented in reactnativerenderer-dev.js, a file with a little more than 2W lines of code.
  • React.development. js: pure JS side react related definitions and simple implementation.
  • The react. Which s: Interface definition, as shown in the local directory/Applications/WebStorm app/Contents/plugins/JavaScriptLanguage/jsLanguageServicesImpl/external/react which s.
# source directory/Users/shengshuqiang/dream/AdvanceOnReactNative/AwesomeProject/node_modules ├ ─ ─ the react │ └ ─ ─ CJS │ └ ─ ─ └─ react-native ├─ Libraries ├─ Components ├─ ├─ exercises, ├─ exercises, exercises, exercises, exercises Print the call stack log and dump Fiber double tree information, about 600 lines of └ ─ ─ ReactNativeRenderer - dev. Js # ReactNative upper core implementation, js code about 2 wCopy the code

trek

A blog, a Demo, a log, an interruption point, a big guess, a proof, a result, a conclusion.

  1. Start by reading a lot of tech blogs and building a knowledge map.
  2. Write a Demo and get a kick out of it.
  3. In order to avoid from the entry to give up, be sure to look at the first log road, after the break point immersed in moving bricks. Slightly more complex algorithms, usually up is a large loop and deep recursion, no strong goal oriented, only GG.
  4. It’s time to unleash your wild imagination, Why? What? How?
  5. Take questions to find answers, go back to the source.
  6. Go back and summarize. What is the point of answering? Can you justify yourself? Can you bluff people who don’t understand (including myself)?

After all this, I can’t remember. Abstractly, this is the technology of navigating in the vast sea. It is called “navigation”.

With simple algorithms, this is basically enough, otherwise it’s really hard to make money. But the Fiber algorithm, it’s really hard. The first round was a jumble of calls with all sorts of weird Fiber properties and complex tree data structures, double trees.

That’s, uh, impossible to remember in a little book. Take a picture of my notes (no need to read it, I’m not going to talk about this picture, everyone see the meaning). After a wave of operation, it takes almost 2 days to shut down and focus on investment. If interrupted, you can’t find the north.

Follow this routine, even log plus debug belt guess-and-guess, found that can’t go on, I am too difficult. Once fell into the valley of despair, struggling to read the source code three times (after all, I hope this wave of wealth), still nothing, waiting for the Epiphany.

light

Until that day, I was waiting for this variable — would it be possible to break the React technology barrier if WE could visualize the state change of Fiber dual-tree while running?

As a bit more intelligent, I thought, “Can I write a script to draw the Fiber double tree?” Then I asked, “Can I write a plugin to draw the Fiber double tree at runtime in real time?” Then I asked, “Draw the real-time method call tree (looks like abstract syntax tree), is that a problem?” What’s the problem? No problem. Let’s do it.

In the end, “HNA technique” through the log and debug read source direction is no problem, the problem is only through the analysis of tens of thousands of log information, the process is boring, it is difficult to imagine the series of so many levels of information. If you use tools to increase productivity and visualize visualized log information, you can gain momentum. Especially for this kind of abstract tree structure, nothing is more straightforward than drawing.

Follow the **DRY (Dont Repeat Yourself) ** principle and iterate over the plug-in step by step. Of course, the process is difficult and cannot be accomplished overnight. The react-DevTools plugin came to mind because Li had recommended it to help analyze Virtual DOM trees, and at that time the team was also extending it. Access plug-in was not sure at that time, ostensibly to expand the success of the battle, but may also be dragged into a new quagmire, neglect the root. Fortunately good luck, in the bottleneck period through Dong Siwen and Chen Zhuo double cattle under the point, ash often smoothly out.

I have to give React Developer Tools 32 thumbs up. It’s the best architecture I’ve seen so far. I’m a bit stubborn about JS. Imitate the existing script a Ctrl+F, Ctrl+C, Ctrl+V became, the ductility can be seen, not accept.

Big hna operation

“Hna art” general direction (log, debug, imagination) is correct, this imagination operation space is too large, is a non-standard product. “Big hna art” big in the visualization of imagination.

  1. In order toThe React method calls the treeFor the main line, monitor every method call, take care of every detail, and figure out who it is, where it’s coming from, and where it’s going. At the same time, with Fiber node operation as the milestone, the current Fiber tree (Fiber double-tree graph data source) is dumped to derive the availabilityTime travelSlow-motion playback for step-by-step exploration.

  2. In order toFiber double tree graphFor small cause and effect, make clear each change in the Fiber tree. The core of the Fiber algorithm is the piecewise manipulation of the Fiber tree to calculate the side effects (DOM manipulation) and then commit once (refresh the page). What is it like to read with questions?

  3. In order toNative View tree graphFor watershed, explain each change of Native View tree. The goal of the Fiber algorithm is to generate a series of instructions to operate the Native View tree.

Let’s enjoy the visual feast of Hna Art.

See the Html Demo page for more information.

User mode (shallow water)

React documentation and simple debugs will take care of most of the problems (if you know what the problem is), and time will do the rest (time is both an antidote and a poison).

Component API

Component variables/methods concept Call time role Best practices
props attribute Set properties when used

This. Props to read
Stores information passed by the parent component 1. UI components, purely displayed according to attributes, have no internal logic
state state SetState sets

Read this. The state
Stores the self-maintained status 1. Container components, pure logic processing, through the combination of UI components to complete rendering

2. The constructor assigns this. State directly. Otherwise setState replaces

3. Reverse mode: Copy prop directly to State
constructor The constructor Before the React component is mounted Used to create component instances 1. Initialize state or method binding, otherwise no implementation is required

2. Not the only entry to pass props (only an initial call, no subsequent updates to props)

3. Super (props) must be called before this. Props
setState Set the state of User active call Changes are queued and rerendered notified 1. Control impact component granularity to avoid mass refresh (performance killer)

2. Distinguish between life cycles in which setState cannot be called to avoid endless loops

3. Only the data that affects the display state of the component is stored in state. Other data can be stored in member variables

4. Components are not always updated immediately, and batch updates are delayed
forceUpdate Forced to update User active call Skip shouldComponentUpdate and trigger Render directly 1. Use with caution

2. If the render method depends on other data, forceUpdate can be called to force a refresh
render Apply colours to a drawing

The only thing that must be done
The Diff is before Describes the appearance level of the current component 1. Properly encapsulate components to ensure readability and maintainability

2. Reduce the inline function

3. Develop good programming habits (scalability, robustness, reliability, ease of use, portability, etc.)

The life cycle

Each component contains “lifecycle methods” that you can override to execute at specific stages of the run.

The life cycle concept type Call time Call the number Call setState role Best practices
static getDerivedStateFromProps Gets the state from the property Conventional methods Called before the Render method is called (both for initial mount and subsequent updates) Many times Not supported (cannot hold references) Return an object to update state (null updates nothing) The value applicable to state depends on props at any time
getSnapshotBeforeUpdate Get snapshot callback before update The new method Called before the last render output (committed to the DOM node) Many times support Enables components to capture information from the DOM before changes are made Uncommon and may occur in UI processing (e.g. scroll position)
componentDidUpdate The component has updated the callback The new method Is called immediately after an update (not when first rendering and shouldComponentUpdate returns false) Many times support This is where you can manipulate the DOM when the component is updated Trigger logic after comparing the props before and after the update (trigger network request when the props changes)
componentWillMount

UNSAFE_componentWillMount
Component to mount callback Abandoned method Called before mounting At a time support Trigger the pre-mount logic Avoid introducing any side effects or subscriptions into this method (use componentDidMount instead)
componentWillReceiveProps

UNSAFE_componentWillReceiveProps
Component to receive property callback Abandoned method Called before the mounted component receives the new props (initial render and setState are not called) Many times support Used to trigger logic before receiving attributes 1. Not recommended (bugs and inconsistencies are common)

2. Update status in response to prop changes
componentWillUpdate

UNSAFE_componentWillUpdate
Component to update callback Abandoned method Called before rendering when the component receives new props or state (the initial rendering and shouldComponentUpdate return false are not called) Many times Not supported (to avoid circular calls) Used to trigger component pre-update logic Not recommended (use componentDidUpdate instead)
componentDidMount The component has mounted the callback Conventional methods Called immediately after the component is mounted (inserted into the DOM tree) At a time support Used to trigger the post-mount logic Initialization that depends on DOM nodes (adding subscriptions, network requests) should be done here
shouldComponentUpdate Whether the component is updated Conventional methods This is called when props or state changes before rendering execution (not when first rendering or forceUpdate is used) Many times Not supported (to avoid circular calls) Reduce unnecessary rendering (performance optimization) 1. Consider using the built-in PureComponent

2. Deep comparisons are not recommended (performance killer)
componentWillUnmount Component to uninstall callback Conventional methods Called directly before the component is uninstalled and destroyed At a time Not supported (this component will never be re-rendered and mounted) Used to trigger pre-uninstallation logic Perform necessary cleanup operations (clear timers, cancel network requests, unsubscribe, and so on)
componentDidCatch Child component error callback Conventional methods Called after a child component throws an error Many times support Used to record errors Error Reporting Log

Remark:

  • When new and obsolete life cycles are mixed, only the new life cycle is known.
  • The premise for calling setState in the lifecycle is: There is no cyclic call risk (shouldComponentUpdate and componentWillUpdate call will lead to cyclic call), limited (must be wrapped in the conditional) condition to run the call, meaningful (componentWillUnmount call meaningless), can call (S) Tatic getDerivedStateFromProps cannot be called), see React setState implementation mechanisms and loop call risks.

Core state (deep water)

The React component is a function of data, v = f(d). Grasp the input and output, to have a target. This analysis is divided into two sections, the initial rendering timeline (the user enters the page what Fiber algorithm does), the user clicks the rendering timeline (the user clicks the button to switch the text to the icon, what Fiber algorithm does). These two scenarios are the root of all Fiber algorithm behavior, and they are all the same. And then I’ll review it with simple pseudocode.

Initial render timeline

Initialize the page layout (there are a lot more components than we wrote)

Initialize JS2Native communication (communication is mainly created by bridge UIManager call createView, setChildren association, and updateView update)

1. Invoke uimanager.createView [3,"RCTRawText",11,{"text":" 0"}] 2 [5,"RCTText",11,{"ellipsizeMode":"tail","allowFontScaling":true,"accessible":true,"fontSize":30,"color":-1,"textAlignVer tical":"center","textAlign":"center"}] 3. invoke UIManager.setChildren [5,[3]] 4. invoke UIManager.createView [7,"RCTView",11,{"backgroundColor":-65536,"height":150,"width":300,"accessible":true}] 5. invoke UIManager.setChildren [7,[5]] 6. invoke UIManager.createView [9,"RCTView",11,{"flex":1,"pointerEvents":"box-none","collapsable":true}] 7. invoke UIManager.setChildren [9,[7]] 8. 9. invoke UIManager.createView [13,"RCTView",11,{"pointerEvents":"box-none","flex":1}] 10. invoke UIManager.setChildren [13,[9]] 11. 12. invoke UIManager.setChildren [11,[13]]Copy the code

Initialize the Fiber tree

Initialize the NativeView tree

Look across the phone

The user clicks on the Render timeline

The user clicks on the page component layout

The user clicks on JS2Native communication,

Measure [7,27] 1. Invoke uimanager.playtouchsound [] 2. Invoke uimanager.createview [15,"RCTImageView",11,{"loadingIndicatorSrc":null,"defaultSrc":null,"src":[{"uri":"http://demo.sc.chinaz.com/Files/pic/i Cons / 5918 / c12. PNG}], "" shouldNotifyLoadEvents" : false, "opacity" : 0.85, "overflow" : "hidden", "height" : 100, the "width" : 100}] 3. invoke UIManager.manageChildren [7,[],[],[],[],[0]] 4. invoke UIManager.manageChildren [7,[],[],[15],[0],[]] 5. invoke UIManager.updateView [7,"RCTView",{"backgroundColor":-16777216}] 1. invoke UIManager.updateView [15,"RCTImageView",{"opacity":null}] 2. invoke UIManager.updateView [7,"RCTView",{"backgroundColor":-65536}]Copy the code

The user clicks the Fiber tree

The user clicks on the NativeView tree

Look across the phone

summary

Parsimonious pseudocode

Talk is cheap. Show me the code.

See parsimonious pseudocode

Method call diagram

With the results

QA

  1. Q: There are only a few components in the React Developer Tools. You can see a bunch of layouts, including Context.Consumer.

    A: Look at the view.js source code and see that it will render context.consumer again. That’s what we wrote <View></View> and the resulting tree is





    Again, <Text></Text> corresponds





    The component we’re writing is actually going to have a layer around it, like yellowbox

  2. Q: The React component and Native do not seem to correspond one to one. What is the mapping strategy?

    A: Only the HostComponent and HostText types map to Native View. The other types do not. They are only used for operations and state logging.

    1. The ReactDOM tree we see with React – devTools is not complete. Here’s what appears on react-devTools:, the text node does not have the actual outermost HostRoot node.

    2. In the ReactDOM tree, only part of DOM nodes (host nodes, corresponding texts and Native components) are displayed on the interface, while others are not. The tag in Fiber represents the type. When creating the NativeView (createInstance and createTextInstance), the tag is the unique identifier of the component. The tag is generated starting from the number 3 and accumulating 2.

    .
  3. Q: What is the relationship between Element, Instance, and DOM?

    A:
  4. React has a diffing algorithm. How does the code compare with the diff algorithm?

    A: Diffing algorithm inReconciliation moduleInside, the corresponding function is ChildReconciler.For the reconcileSingleTextNode and reconcileChildrenArray, see reconcileSingleTextNode and reconcileChildrenArray. For more informationReact Diff – React Diff.
  5. ShouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate

    ShouldComponentUpdate () shouldComponentUpdate (); shouldComponentUpdate (); shouldComponentUpdate ();
  6. React has a DOM tree. How to operate a Native DOM tree? A: On my extension plugin.
  7. Q: What exactly does setState do? A: Trigger Fiber double-tree re-diff rendering using method call tree tracing.
  8. Q: How efficient is React? A: Priority – based tree traversal algorithm can be interrupted, and the diff algorithm complexity O (n).
  9. Q: React workflow? Answer: It is in the article.
  10. Q: How to associate Native custom components? A: That’s a good question and I’ll leave it to the reader.
  11. Q: What are the attributes of the Fiber node data structure?

    A:

    1. Return, child, sibling:



    2. Key: reuse the id.

    3. Tag: It is used in the coordination algorithm to determine the work that needs to be done. As mentioned earlier, the work depends on the type of the React element.

    4. StateNode: Holds references to the component’s class instance, DOM node, or other React element types associated with the Fiber node. In general, we can think of this property as being used to preserve the local state associated with a Fiber node.

    A. HostRoot corresponds to {containerInfo}.

    B. ClassComponent corresponds to an instance of a function object called new.

    C. HostComponent corresponding ReactNativeFiberHostComponent, contains _children and _nativeTag.

    D. HostText corresponds to nativeTag.

    5. ElementType/Type: describes its corresponding component. For composite components, the type is a function or the class component itself. For host components (div, SPAN, and so on), the type is a string. Defines a function or class for this Fiber node. For class components, it points to constructors, and for DOM elements, it specifies HTML tags. I often use this field to understand which element the Fiber node is associated with.

    A. ClassComponent corresponds to functions, such as APPContainer().

    {$$typeof: Symbol(react.forward_ref), render: ƒ, displayName: “The View”}.

    C. HostComponent is a string, for example, RCTView.

    D. The value of HostText is NULL. E. memoizedProps: The props used to create the output Fiber in the previous render.

    F. MemoizedState: Fiber state for creating output. When an update is processed, it reflects the current state rendered on the screen.

    G. pendingProps: props is an argument to a function. A Fiber pendingProps is set at the beginning of execution and memoizedProps is set at the end. Props that have been updated from new data in the React element and need to be applied to child components or DOM elements.

    H. UpdateQueue: state updateQueue. Queues for status updates, callbacks, and DOM updates.

    I. firstEffect, lastEffect and other devices are used to save the state of effect before and after interruption, and users can resume the previous operations after interruption. This is confusing because Fiber uses interruptible architecture.

    J. EffectTag: Side effects.

    K. alternate: After calling render or setState, a mirror fiber is cloned, and diff changes are marked on the mirror fiber. Alternate is the link between the current Fiber Tree and the mirror Fiber Tree for breakpoint recovery. Each node in the workInProgress Tree has an Effect List to store the content that needs to be updated. After this node is updated, the effect List is merged with its children or neighboring nodes.

High performance practices

Give your browser a good rest and it will run faster.

I’ll save it for the next time.

Problem location tool

Based on the above plug-in, the same development.

Methods the hook

I can write another article about how my data mapping came about and how this plugin was written.

A long song

  1. Never be satisfied with what the world looks like. Dare to explore what is possible. — Overwatch
  2. Heaven never gave birth to me li Chungang, kendo is as long as night. Sword! “– Knifes in the Snow
  3. In Ben shuai’s eyes, there is no saint, there is no king. — Bad Man painting rivers and Lakes
  4. The world is full of changes and changes, even though it changes, but the heart of the change, there is no matter not to do, day is to win, man is xi victory day! Li Chunfeng, how about hegemony? How about the way of heaven? I don’t care. — Bad Man painting rivers and Lakes
  5. The three realms are idealist, and the dharma is only conscious. The mind changes, but knowledge shows. — Buddha Dharma
  6. Seeks the inverse? ! Hahahaha! I’m not afraid of treason, but start all over again! — Eve by Holy Fire
  7. While others blindly follow the truth, remember that everything is empty; While others are constrained by morality and law, remember that everything is acceptable. We bow to the darkness and serve the light. — Assassin’s Creed
  8. Nature of all things to nurture people, the world still complain. — The Seven Slain Stele
  9. Good boy, don’t parents, only for the common people not main. — “Red Scarf Army Song”

conclusion

Thank your mother-in-law and daughter-in-law for their silent efforts, thanks to shixing big brother, Asxu God, Che Hao big brother, Zhang Jie big brother, Siwen Dana, Chen Zhuo Danu for their technical support and guidance.

I once saw a question in Zhihu, “What level of front-end can be used to change the React-Native source code?” I challenged the level.

Airbnb shook its head, said “RN is too hard” and collapsed. But we must stand up and lead

This is a tribute to those who loved Internet technology and spent time with the people who fought with them.

reference

  1. React16 source code React Fiber architecture
  2. The React Fiber architecture
  3. React Fiber stuff: An in-depth look at the new coordination algorithm
  4. React Diff and Fiber
  5. React with 200 lines of code
  6. React Diff – React Diff
  7. React source code
  8. [React] React Fiber
  9. Introduction to Virtual DOM and React Fiber
  10. React: A problem no one can explain — why use the Virtual DOM
  11. How to implement a Virtual DOM algorithm #13
  12. React Fiber architecture
  13. What is React Fiber
  14. Brief introduction to Act16 frame-Fiber
  15. React Fiber Architecture
  16. React 16 Architecture Research Notes
  17. Understand the React lifecycle
  18. React
  19. React Native
  20. react-devtools