First, let's take a look at the popularity trend of React around the world. The figure below is a comparison of the search volume of the keywords "housing prices" and "React" on Google Trends. The blue one is React and the red one is housing prices. It is obvious that people's attention to React has far exceeded that to housing prices. What can you tell from these data? It's obvious that I'm talking nonsense. Comparing the popularity trends of React, jQuery, and Angular from 2014 to now, we can clearly see (see the picture above) that React's popularity is growing very fast around the world. The above picture is the Baidu search index of React in China. It compares React and Nodejs. It can be seen that the attention paid to React is approaching that of Nodejs. Although React is still far behind jQuery and Angular in terms of total attention, its growth rate is beyond your imagination. Do you know what this means? This means that by paying attention to React, you are at the forefront of the industry than most people!
So what exactly is React? Quoting the official website's introduction, "a JavaScript library for building user interfaces." React originated from an internal project of Facebook. Because FB was not satisfied with all the JavaScript MVC frameworks on the market, they decided to write their own to build the Instagram website. After it was completed, they found that this system was very useful, so they open-sourced it in May 2013. Since React's design concept is extremely unique, it is a revolutionary innovation, has outstanding performance, and has very simple code logic. Therefore, more and more people are beginning to pay attention to and use it, believing that it may be the mainstream tool for Web development in the future. Unlike Backbone, Angular and other MV* frameworks, it only handles View logic, so if you like it, you can easily integrate it into the existing project, and then rewrite the HTML part with React without modifying the logic. In recent years, the technological innovation in the web field has been very rapid, and React is also a new technology... React has been out for 2 years. In fact, it is not a new technology, but it has not been popularized in China. The purpose of this article is to help everyone understand react more quickly and recognize the value that react can bring to us.
React is so popular, so what’s so great about it? The above figure shows the data at the beginning of 2015
This is the Facebook Friends Dynamics page, which is also the most visited page on Facebook. Through the Chrome React plug-in, you can see that this page is indeed implemented with React. (A colleague asked me why I follow Liu Yan, and I said it’s because I’m a fan of Liu Yan) I've given you a bit of foreplay before, and I believe you're already a bit impatient, so let's get to the point: First, let me describe to you the most special part of React. After listening to this part, you will basically be able to build a general impression of React in your mind. Then comes the core content of React. After listening to this part, you can go back and start writing code and release it online tonight. The last thing is the actual value that React can bring to us. We will not do meaningless code refactoring. First, let’s look at JSX —
JSX uses precompiled templates. React provides a precompilation tool called react-tools, which can be installed through the npm command. It is usually run during the development period. After running, it will start a monitoring program to monitor the modification of JSX source code in real time, and then automatically compile it into JS code. Please note that the render() method is compiled into React.createElement(). It does this to implement the virtual DOM.
Next, let's take a look at the highlight of React————Virtual DOM. Traditional web apps interact directly with the DOM, and the App controls the construction and rendering of the DOM, the reading and writing of element attributes, the registration and destruction of events, etc. This approach seems to be good when a new product is just launched. However, as the product features become richer, the amount of code increases, and the number of development team members increases— One year later Your code might become like this. Of course, reasonable code planning can avoid such problems, but there will inevitably be students in the team who are good at butcher-style programming and can change your code beyond recognition in minutes. #p# At this time, React's virtual DOM and unidirectional data flow can solve this problem well. Virtual DOM builds an abstraction layer based on DOM. Any changes we make to data and status will be automatically and efficiently synchronized to virtual DOM, and then synchronized to DOM in batches. Virtual DOM will make the App only care about the execution results of data and components. The DOM operations generated in the middle do not require App intervention. In addition, generating DOM through virtual DOM will have a very considerable benefit - performance. Everyone knows that DOM is slow. To render an empty DIV, the browser needs to generate hundreds of attributes for this DIV, while the virtual DOM only has 6. Therefore, reducing unnecessary reflow and redrawing as well as DOM reading and writing can greatly improve page rendering performance. Let's take a look at how virtual DOM works: React maintains a virtual DOM tree in memory. When we read or write to this tree, we are actually doing it to the virtual DOM. When the data changes, React will automatically update the virtual DOM, and then compare the new virtual DOM with the old virtual DOM to find the changed part, get a Patch, and then put the Patch in a queue, and finally update these Patches to the DOM in batches. This mechanism ensures that even if the root node data changes, the modification ultimately reflected in the DOM is only the part affected by this data, which can ensure very efficient rendering. But this also has certain flaws----***When rendering a large amount of DOM, because of the extra layer of virtual DOM calculation, it will be slower than the innerHTML insertion method, so when using it, you need to make sure not to render a large amount of DOM at one time. Comparison of rendering performance of several UI components http://mathieuancelin.github.io/js-repaint-perfs/
A basic React component consists of two main parts: data and JSX. Let's take a look at the data first. This is a simple but complete React component [class]. You don’t need to pay too much attention to the details for now, just understand the mechanism. The main function of props is to provide data sources, which can be simply understood as props are the parameters of the constructor. The only function of state is to control the performance of the component, and is used to store states that change with interaction, such as switch states. What JSX does is to output the corresponding DOM structure based on the values in state and props, combined with some view-level logic.
Earlier we learned about the composition of a simple component, but a single component certainly cannot meet actual needs. What we need to do is to assemble these independent components and find the common parts for reuse. For example, a scene like this Let's take this interface as an example. We can see that <Pub/> <Article/> are the finest-grained components and can be reused. First, let's look at the code for Article. This is the Article component we decomposed. It needs two properties, article object and showImage. The article object contains pictures, addresses, titles, and descriptions. showImage is a Boolean type, which is used to determine whether it needs to be displayed as an image. The implementation of this component itself can be very simple or very complex, but the user does not care about your internal implementation. The user only cares about what parameters the component requires. The componentization concept of foreigners is much more popular than that in our country. It is not limited to software development, but also includes coffee machines, gas stations, and children's rocking cars in the physical industry. This design concept is included.
I hope that when designing modules, you will make the component logic as transparent as possible to reduce maintenance costs. Please pay attention to the dotted part, where the Article component is reused. At this time, the Article component looks like an ordinary label, simple, right? This is a hot component, which also reuses the Article component. This is React's silky-smooth component composition.
This is called a bamboo sieve, which is a common garden decoration in traditional Chinese and Japanese Zen culture. Its structure can be simple or complex, but the principle is very simple. For example, water flows into the bamboo sieve from the top entrance, and flows into each small bamboo tube from top to bottom in a fixed order, and then drives the water wheel to rotate. For people with obsessive-compulsive disorder, watching the bamboo sieve is definitely a very enjoyable process. You will find that these little gadgets can be coordinated so smoothly, which is amazing.
If the bamboo shoot is a component, then the water is the data flow of the component. In React, data flows from parent nodes to child nodes in a one-way manner from top to bottom, so components are simple and easy to grasp. They only need to get data from the props provided by the parent node and render. If a prop of the top-level component changes, React will recursively traverse the entire component tree and re-render all components that use this property. This is the Article component we saw earlier, which has a property called articles. Inside a component, you can access props through this.props. Props is the only source of data for a component. For a component: Props are always read-only. #p# If the component's attribute type is not declared and verified, it is very likely that the attribute value or type passed to you by the user is invalid, which will cause some unexpected failures. Fortunately, React has provided us with a very simple and easy-to-use attribute verification mechanism - React has a PropTypes property validation tool that can be easily configured. When the parameters passed in by the user do not meet the validation rules, React will give a very detailed warning, making it easy to locate the problem. PropTypes contains validation types including basic types, arrays, objects, instances, and enumerations. And in-depth validation of object types, etc. If the built-in validation types do not meet your needs, you can also validate through custom rules. If a property is required, add .isRequired after the type. A major innovation of React is to regard each component as a state machine, and use state inside the component to maintain changes in component state. This is also the only function of state. State is generally used together with events. Let’s look at state first, and then see how state and events are combined. This is a simple switch component. The switch state will be displayed in the form of text on the button text. First, let’s look at the render method. It returns a button element, registers an event for the button to handle click events, negates the on field of state in the click event, and executes the this.setState() method to set the new value of the on field. A switch component is now complete.
After the component is rendered, it must have the support of UI events to work properly. React handles events by binding event handlers to components. React events are essentially the same as native JS. Mouse events are used to handle click operations, and form events are used for form element changes. The naming and behavior of React events are similar to native JS. The only difference is that React event names are case sensitive. For example, in this code, the section node of the Article component registers an onClick event, and an alert pops up when clicked. Sometimes, the event handler needs to be provided by the user of the component, in which case the event handler can be passed in via props. This is the user of the Article component. The props it provides to the Article component include an onClick attribute. This onClick points to an event handler of the component itself, thus realizing the processing of event callbacks outside the component. This is the process required for a React component to make the component interactive. render() outputs the virtual DOM, the virtual DOM is converted to DOM, and then events are registered on the DOM. The events trigger setState() to modify the data. Each time the setState method is called, React will automatically execute the render method to update the virtual DOM. If the component has been rendered, it will also be updated to the DOM. These are the list of events currently supported by React.
React components have a clear, complete and very easy to understand life cycle mechanism, which can be roughly divided into three processes: initialization, update and destruction. During the component life cycle, as the props or state of the component changes, its virtual DOM and DOM performance will also change accordingly. The first is the initialization process, which will be emphasized here and needs to be fully understood. When a component class is declared, the getDefaultProps() method is called first to obtain the default props value. This method will be called only once when the component class is declared. It should be noted that the default props it returns are shared by all instances. Before a component is instantiated, the instance method getInitialState() is called once to obtain the initial state of the component. After instantiation, it is time to render. The componentWillMount method will be called before the virtual DOM is generated. You can do some preparation for the rendering of the component here, such as calculating the target container size and then modifying the component's own size to adapt to the target container, etc. Next comes rendering, where you create a virtual DOM to represent the structure of the component. For a component, render is the only required method. The render method needs to meet the following requirements:
It should be noted that the render method returns a virtual DOM. After rendering is complete, we may need to do some operations on the DOM, such as taking screenshots, reporting logs, or initializing third-party non-React plug-ins such as iScroll. You can do these things in the componentDidMount() method. Of course, you can also get the final generated DOM node through the this.getDOMNode() method in this method, and then do whatever you want with the DOM node, but you need to take safety measures and do not cache the generated DOM nodes, because these DOM nodes may be replaced at any time, so they should be read each time they are used. After the component is initialized, its state will change with user operations, the passage of time, and data updates. The change process is another part of the component declaration lifecycle. Update process. #p# When a component has been instantiated and the user calls the setProps() method to modify the component's data, the componentWillReceiveProps() method of the component will be called. Here, you can perform some preprocessing on the external data, such as reading data from props and writing it to the state. By default, after a component is setState(), React will traverse all subcomponents of this component, "flood", pass props down layer by layer from top to bottom, and perform update operations one by one. Although many optimizations have been done internally in React, this process does not take much time, but there is always a lack of programmers who are hungry for performance for a long time. Don't worry, React has a way to solve your performance hunger - shouldComponentUpdate() - sometimes, props change, but components and subcomponents do not change because of the change in props. For example, you have a form component, you want to modify the name of the form, and you can be sure that this name will not have any effect on the rendering of the component, then you can directly return false in this method to terminate subsequent behavior. This can avoid invalid virtual DOM comparisons and significantly improve performance. If some students are still eager at this time, then you can try immutable data structures (students who have used Mongodb should understand). Before a component is updated, React will execute the componentWillUpdate() method, which is similar to the componentWillMount() method we saw earlier. The only difference is that the component has already been rendered when this method is executed. It should be noted that props or state cannot be modified in this method. If you want to modify it, you should modify it in componentWillReceiveProps(). Then comes rendering. React will compare the virtual DOM returned this time with the virtual DOM in the cache, find the [minimum modification point], and then replace it. After the update is complete, React will call the component's componentDidUpdate method, which is similar to the previous componentDidMount method. You can still get the final DOM node here through the this.getDOMNode() method. At the end of Hong Kong movies, we often see a plot where the hero defeats the bad guy, and then the police come out to clean up the mess.
componentWillUnmount can't do anything except clean up the mess. You can destroy events registered by non-React components, inserted nodes, or some timers in this method. This process may be prone to errors, such as binding events but not destroying them. React can't help you with this. You have to finish the game you made up your mind, even if you cry. Next, let's take a look at how React can be combined with nodejs to achieve server-side rendering.
I won’t say much about how fast server-side rendering is. Because of the existence of virtual DOM, React can easily convert virtual DOM into a string, which allows us to write only one UI code and run it in both node and browser. var html = React.renderToString(elem); Rendering react component HTML to HTML in node is just one line of code. However, we still need to do some preparation around this renderToString: 1. Pull data from the background server or database and other sources 2. Call React.renderToString() method to generate HTML 3. *** Send HTML and data to the browser I won’t post the code, you can use your imagination. It should be noted that the JSON string here may contain a </script> ending tag or HTML comment, which may cause syntax errors and needs to be escaped. The sample code of the page was originally intended to use HTML, which is more familiar to everyone, but I found that the amount of code was too much, so I changed it to jade code. Students who have not used jade can also learn about it by the way, and I also advertise jade by the way. This page does the following things: 1. Write the HTML generated in the action to the #container element 2. Import the necessary JS files 3. Get the data provided by the action 4. Render the component This is React's server-side rendering, and the component code can be reused on both the front-end and back-end. React is awesome, right? It’s not over yet!
React can run in both browsers and node with a set of code, and can run in iOS and Android systems as a native app, which means it has both the rapid iteration characteristics of the web and the experience of a native app. This approach is called React-Native. This is the data of React and React-Native on GitHub. It can be seen that React-Native is also quite popular - because React-Native can maximize the value of React. What is this value? - For the business, it means that there is no need to recruit terminal developers with the same amount of manpower as front-end developers in order to make terminal versions. It also means that we have a shortcut to becoming full-stack engineers.
Those who are familiar with iOS development know that the efficiency of Apple's review of apps on the shelves is really unbearable. Many teams have already completed the next version before the previous version is reviewed. React-Native supports pulling JS from the network, so iOS apps can also be quickly iterated like web apps. The above picture shows the debugging process of react-native, taking iOS as an example
Of course, react is not perfect. You will find some shortcomings in actual use, such as: (If you are only developing Android apps, then the "Apple two-piece package + developer certificate" is not necessary, and you can develop under Windows.) ***, when you use react development, you may need to install React developer tools *** is some reference material There is a path to the mountain of knowledge through diligence, and React is the shortcut to becoming a "full-stack engineer". Introduction to Tencent BuglyBugly is an external version of Tencent's internal product quality monitoring platform. Its main function is to monitor and report crashes and freezes that occur on the user side after the App is released, so that developers can understand the quality of the App in real time and make timely model modifications. Currently, all Tencent's internal products are using it to monitor online product crashes. |
<<: Can Google still make a living if it returns to the Chinese market?
The author of this article has worked for Didi an...
Duan Youqiao, an iQiyi artist, today I suddenly w...
Since Google launched Nexus 7, more diverse sizes...
" Honor of Kings " recently launched it...
On August 25, after removing 62 apps that failed ...
At present, my country's economy is at a crit...
Introduction to the course resources of Han Yuqia...
Author: Su Chengyu The article comes from the Sci...
On September 19, according to foreign media repor...
Although the issue of national trends is always m...
"Ordinary people can also earn over 10,000 y...
The popularity of mobile smart devices also bring...
When it comes to the national snack internet cele...
Resource introduction of the ninth session of Jia...
1. India 1.1 Development and Current Status of Li...