1. React to React-native

Open source by FaceBook in 2013, React is a JavaScript based UI framework (library) that allows you to efficiently draw the DOM with a concise syntax to build “predictable” and “declarative” Web user interfaces. React is not an MVC framework. It focuses on the construction of View layer in MVC. To achieve a complete MVC architecture, Model and Controller structures are needed, such as Flux architecture introduced with React, Redux, Mobx, etc.

Brevity: You can mix JS, CSS, and HTML with JSX (a syntax extension to JS), and only care about how to construct pages in JavaScript, which will eventually be converted to native JavaScript and create the DOM.

Efficient: Original Virtual DOM mechanism. The Virtual DOM is a JavaScript object that exists in memory and has a one-to-one correspondence with the DOM, which means that as long as we have the Virtual DOM, we can render the DOM. When the interface changes, thanks to the efficient DOM Diff algorithm, we can know the changes of the Virtual DOM, thus efficiently changing the DOM without redrawing the DOM. , we can know the changes of the Virtual DOM, so that we can efficiently modify the DOM without redrawing the DOM.

React is a one-way data flow, not a two-way data binding, and does not directly manipulate DOM objects. Most of the time, it only programs the Virtual DOM. The state (data) of the application can be derived from the view and is predictable.

Declarative: Components are the basic unit of React, and with React you just build components. Encapsulation makes component code reuse, testing, and separation of concerns easier.

React-native is a javascripts based mobile development framework for front end developers with dynamic configuration capabilities (for Native hot updates, not only configuration information can be dynamically changed, but also execution logic can be dynamically updated). We can use it to develop both Native experiences (with reservations) and React efficient applications. React uses WebView (browser) as the back end and operates Virtual DOM for view rendering, while React uses ios or android Native controls as the back end. But Expose comes out as a React Component for view rendering.

2. React-naitve framework overview and principles

React: Write code based on React on different platforms, “Learn once, write anywhere”.

Virtual DOM: Compared with DOM in Browser environment, Virtual DOM is a lightweight representation of the document in memory, which can generate UI of different platforms through different rendering engines. JS and Native communicate via Bridge.

Web/iOS/Android: UI interface for upper-layer interaction with users.

React-native abstracts the Native UI components of the operating system in JavaScript to render instead of DOM elements. It uses Native controls of Android or iOS, so its UI rendering is very close to Native apps. Although the business logic code uses JavaScript, JavaScript has to run efficiently because JavaScript is just-in-time compiled, meaning that the JavaScript code is compiled into a binary file the first time it is used. As a result, React Native is much more efficient than PhoneGap and AppCan based on HTML5, CSS and other technologies, because these technologies directly use HTML5 for rendering. However, HTML5 makes extensive use of DOM technology, which consumes a lot of performance.

3. React-native lifecycle

GetDefaultProps: Before the component is created, getDefaultProps() is called once globally. Load components before they are created.

GetInitialState () to initialize the state of the component.

ComponentWillMount: Ready to start loading components. It is called only once in the entire life cycle, where you can do some business initialization and also set the component state.

ComponentDidMount: Called after a component has been drawn for the first time. When this function is called, the virtual DOM has been built and you can start retrieving elements or child components. Note that the RN framework calls the child’s componentDidMount() and then the parent’s function. From this function, you can interact with other JS frameworks, such as setting a timer setTimeout or making a network request. After this function, it enters a stable state, waiting for the event to fire.

ComponentWillReceiveProps: If the component received new props, is called componentWillReceiveProps (), within the callback function, you can according to the variation of properties, by calling the enclosing setState () to update your component state, This call does not trigger an additional render() call.

ShouldComponentUpdate: This is a call to shouldComponentUpdate(…) when the component receives new properties and state changes. The return value of this function determines whether the component needs to be updated. If true indicates that the component needs to be updated, continue with the update process. If no, the system does not update the data and enters the waiting state directly.

ComponentWillUpdate: If component state or properties change, and shouldComponentUpdate(…) Return true to start the quasi-update component and call componentWillUpdate(), in which you do the things you would have done before updating the interface. Note that in this function, you cannot use this.setState to change the state. Following this function, render() is called to update the interface

ComponentDidUpdate: After calling Render () to update the interface, componentDidUpdate() is called to be notified.

ComponentWillUnmount () is called when a component is to be removed from the interface. In this function, you can do component-related cleanup, such as canceling timers, network requests, and so on.

4. React-native/Native interaction (communication mechanism Eg: ios)

As mentioned above, React Native uses Native controls of Android or iOS to do UI rendering, so we need Native frameworks such as UIKit to call Objective-C code or Java code, and we also need to run JS code in Native code. For example, events registered on UI controls require communication between the JS side and the native side.

As we all know, JavaScript is a scripting language, which does not go through compilation, linking and other operations. Instead, it performs lexical and syntax analysis dynamically at runtime, generates abstract syntax tree (AST) and bytecode, which is then executed by the interpreter or converted into machine code by JIT. The whole process is done by a JavaScript engine, and IOS provides a framework called JavaScript Core, which is a JavaScript engine. To get a feel for how Objective-C calls JavaScript code:

JSContext refers to the runtime environment for JavaScript code that can be executed and returned via evaluateScript.

JavaScript is a single-threaded language. It doesn’t have the ability to run itself, so it’s always called passively. Objective-c creates a single thread that only executes JavaScript code, and the JavaScript code only executes in that thread.

The interaction process

In React Native, Objective-C and JavaScript interactions are all done by passing ModuleId, MethodId, and Arguments. Both objective-C and JavaScript keep a configuration table that marks all objective-C modules and methods exposed to JavaScript. Thus, no matter which party calls the other party’s method, only the ModuleId, MethodId, and Arguments elements are actually passed, representing the class, method, and method Arguments, respectively. When Objective-C receives these three values, The Runtime uniquely determines which function to call, and then calls it. Objective-c interaction with JavaScript is always initiated by Objective-C. The interaction between Object-C and JS is carried out through the Bridge and ModuleConfig at each end. The actual process can be divided into two stages: initialization stage and method call stage.

Initialize React Native

In an RN (ios) project, there will always be a file called appdelegate. m, which has the following code:

Everything the user sees comes from this RootView, and all initialization is done within this method. Inside this method, React Native actually creates a Bridge object before creating a RootView. It is the bridge between Objective-C and JavaScript, the subsequent method interactions are entirely dependent on it, and the end goal of the initialization process is to create the bridge object.

The core of the initialization method is the setUp method, and the main task of the setUp method is to create BatchedBridge. BatchedBridge is used to batch read JavaScript method calls to Objective-C, and it holds an internal JavaScriptExecutor, which, as the name implies, executes JavaScript code. The key to creating BatchedBridge is the start method, which can be divided into five steps:

Read JavaScript source code

The JavaScript code runs in an objective-C environment, so the first step is to load the JavaScript into memory. For an empty project, all the JavaScript code takes up about 1.5 Mb of memory space. In this step, the JSX code has been converted to native JavaScript code.

Example Initialize module information

The main task is to find all the classes (modules) that need to be exposed to JavaScript

Initializes the executor of the JavaScript code, the RCTJSCExecutor object

Initializes the JavaScript code executor while adding blocks (the implementation of closures in Object-C) as global variables to the JavaScript context.

Block – nativeRequireModuleConfig: it calls in JavaScript registered a new module:

Block – nativeFlushQueueImmediate: In general, Objective-C will periodically and actively call the methods that JS put into MessageQueue. In fact (due to lag or some special reason), JavaScript can also actively call Objective-C methods. Currently, React Native logic is that if there is logic in the message queue waiting for objective-c to process, and objective-c does not pick it up for more than 5ms, JavaScript will actively call objective-c methods.

Keep this 5MS in mind, which tells us that JavaScript interacting with Objective-C has some overhead, or you don’t wait and start requesting immediately every time. Second, the time overhead is about milliseconds, not much less than 5ms, otherwise it wouldn’t make sense to wait so long.

Generate a list of modules and write to the JavaScript side

Let JavaScript get the names of all modules and store them as a global variable

Executing JavaScript source code

Run the code, add in the third step of Block (nativeRequireModuleConfig) will be performed, thus to write configuration information for the JavaScript side.

Initialization engineering

The method call

OC calls JS code

The OC does not call the actual JS function directly. Instead, the OC calls the maintained transition function. The transition function receives Arguments including ModuleId, MethodId, and Arguments, and can search its module configuration table to find the JavaScript function to call.

2. JS invokes OC code

When calling Objective-C code, JavaScript will parse the ModuleId, MethodId, and Arguments of the method into MessageQueue and wait for Objective-C to take them away. Or you can actively send it to Objective-C after a timeout.

Internally, the function looks up the module configuration table in each power call to find the method to call, and makes the call dynamically through the Runtime.

5. React Native

advantages

Reusing React ideas helps front-end developers get their foot in the door on mobile.

Able to take advantage of JavaScript dynamic update features, fast iteration.

The development speed is faster than the native platform and the performance is better than the Hybrid framework.

disadvantages

Write Once and Run Everywhere are not possible, which means developers still need to provide two different sets of code for the iOS and Android platforms. For example, if you look at the official documentation, you can find many components and apis that distinguish between the Android and iOS versions. Even if components are shared, there will be platform-specific functions.

You can’t completely block out the details of iOS or Android, but the front-end developer must have some knowledge of the native platform. Increase the cost of learning. React Native is completely unavailable to mobile developers.

Due to the fixed time overhead of switching between Objective-C and JavaScript, performance is bound to be inferior to native. For example, the current official version of the UItableview(ListView) does not allow for view reuse, because the view reuse needs to be performed in asynchronous threads during sliding, which is too slow. This leads to a linear increase in memory usage as the number of cells increases.

The resources

React Native official documentation

React Native Official Document Chinese version

React Native communication mechanism

React Example tutorial

This article originally himself in Jane books written: www.jianshu.com/p/82a28c8b6… Subsequent articles will be migrated or written directly on nuggets.