In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
How to deeply understand the data flow and event principle, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
In React, the data flow is transmitted from the parent node to the child node one way from top to bottom, so the components are simple and easy to grasp, they only need to get the data from the props provided by the parent node and render it. If a prop of the top-level component changes, React recursively traverses the entire number of components, re-rendering all components that use this property.
This is the KM hotspot component seen earlier, with an attribute called articles.
Within the component, it can be accessed through this.props. Props,props is the only data source for the component, and for the component:
Props is always read-only.
Do not try to call the setProps method inside the component to modify the props. If you do so accidentally, React will report an error and give a very detailed error message.
If the property type of a component is not declared and validated, it is likely that the property value or type passed to you by the user is invalid, which can lead to some unexpected failures. Fortunately, React has provided us with a very simple and easy-to-use attribute verification mechanism--
React has a PropTypes property verification tool that can be easily configured. When the parameters passed by the user do not meet the verification rules, React will give a very detailed warning, so it is not too easy to locate the problem.
PropTypes contains check types including primitive types, arrays, objects, instances, enumerations--
And the in-depth verification of object types, and so on. If the built-in validation type does not meet the requirements, it can also be verified by custom rules.
If an attribute is required, just add isRequired after the type.
One of the great innovations of React is to regard each component as a state machine, and the component maintains the change of component state through state, which is the only function of state.
State is usually used with events. Let's first look at state and then see how state and events combine.
This is a simple switch component, and the switch state is displayed in the text of the button in the form of text.
First look at the render method, which returns a button element, registers an event with button to handle the click event, inverts the on field of the state in the click event, and executes the this.setState () method to set the new value of the on field. A switch assembly is completed.
After the component is rendered, it must be supported by the UI event 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, form events are used for form element changes, and so on. The naming and behavior of Rreact events are similar to native JS, except that React event names are case-sensitive.
For example, in this code, the section node of the Article component registers an onClick event, and the alert pops up when clicked.
Sometimes, the event handler needs to be provided by the consumer of the component, and the event handler can be passed in through the props.
This is the consumer of the Article component, and the props it provides to the Article component contains an onClick property that points to an event handler of the component itself, thus enabling event callbacks to be handled outside the component.
This is a React component to achieve components can interact with the required process, render () output virtual DOM, virtual DOM to DOM, and then register events on the DOM, events trigger setState () to modify 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, then it will also be updated to DOM.
These are lists of events currently supported by React.
The components of React have a set of clear, complete and easy to understand life cycle mechanism, which can be 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 change accordingly.
The first is the initialization process, which will be emphasized here and needs to be fully understood.
When a component class declares, it first calls the getDefaultProps () method to get the default props value, which is called and only once when the component class is declared, which should be noted that the default props it returns is shared by all instances.
Before the component is instantiated, the instance method getInitialState () method is called once to get the initial state of the component.
Rendering is followed by instantiation, and the componentWillMount method is called before generating the virtual DOM, where you can do some preparatory work for the rendering of the component, such as calculating the size of the target container and then modifying the size of the component itself to fit the target container, and so on.
The next step is rendering, where you will create a virtual DOM to represent the structure of the component. Render is the only necessary method for a component. The render method needs to meet these points:
1. Data can only be accessed through this.props or this.state
two。 Only one top-level component can appear
3. You can return null, false, or any React component
4. Cannot modify props, state, or DOM
Note that the render method returns a virtual DOM.
After rendering, we may need to do some operations on DOM, such as taking screenshots, reporting logs, or initializing third-party non-React plug-ins such as iScroll, which can be done 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 what you have sex with the DOM node, but you need to be careful not to cache the generated DOM nodes, because these DOM nodes may be replaced at any time, so you should read them every time you use them.
After the component is initialized, its state changes with the user's operations, time, and data updates, and the process of change is another part of the component declaration cycle--
Update process.
When the component has been instantiated and the consumer calls the setProps () method to modify the component's data, the component's componentWillReceiveProps () method is called, where you can preprocess the externally incoming data, such as reading data from props and writing it to state.
By default, after the user calls the setProps () method of the component, React will traverse all the sub-components of the component, "water", pass the props down from the top to the next layer, and perform the update operation one by one. Although a lot of optimization has been done within React, this process will not take much time, but there is no shortage of long-term performance hungry students among programmers, so don't worry. React has a way to solve your performance hunger-shouldComponentUpdate ().
Sometimes, the props has changed, but the components and subcomponents will not change because of this props change, for example, you have a form component, you want to modify the name of the form, and you can be sure that the name will not have any impact on the rendering of the component, then you can directly return false in this method to terminate the subsequent behavior. In this way, invalid virtual DOM comparisons can be avoided and performance will be significantly improved.
If some students are still hungry at this time, you can try immutable data structures (students who have used mongodb should understand).
Before the component is updated, React executes the componentWillUpdate () method, which is similar to the componentWillMount () method seen earlier, except that the component has already been rendered when the method is executed. It is important to note that props or state cannot be modified in this method, but should be modified in componentWillReceiveProps () if you want to.
Then there is rendering. React will compare the returned virtual DOM with the virtual DOM in the cache to find out the minimum modification point, and then replace it.
When the update is complete, React calls the component's componentDidUpdate method, which is similar to the previous componentDidMount method, where you can still get the final DOM node through the this.getDOMNode () method.
At the end of Hong Kong movies, we often see a plot in which the hero defeats the bad guys, and then the police come out to wipe their buttocks--
The police can do meritorious service occasionally, but componentWillUnmount is the most pitiful. He can do nothing but wipe his ass.
You can destroy events registered by non-React components, inserted nodes, or timers in this method. This process may be prone to error, such as binding the event but not destroying it, this React can not help you, you have to finish it with tears in your own appointment.
Two sections talk about the necessary knowledge to get started with React.
I'll talk about value later.
I won't say much as soon as I get out.
Because of the existence of virtual DOM, React can easily convert virtual DOM into strings, which allows us to write only a copy of UI code and run it in node and browser at the same time.
Render the component HTML in node as a piece of HTML and say a word.
However, we still have to do some preparatory work around this renderToString. There is a lot of code, so be prepared.
This is an express routing method, here:
1. Pull data from sources such as background server or database
two。 Introduce the React components to be rendered
3. Call the React.renderToString () method to generate HTML
4. Finally, send HTML and data to the browser.
Here, in order to facilitate the description, we do not write the code to pull the data, so we can make it up by ourselves.
It is important to note that the end tag or HTML comment may appear in the JSON string here, which may lead to syntax errors, and you need to escape here.
The sample code on the page was intended to use the more familiar HTML, but I found that there was too much code to fit a page in PPT, so I replaced it with jade code. Students who have not used jade also learned by the way that I also advertised jade.
This page does X things:
1. Write the HTML generated previously in action into the # container element
two。 Import the necessary JS files
3. Get the data provided by action
4. Rendering component
This is the server-side rendering of React, and the code of the component can be reused both front and back.
Do you feel that React is quite powerful? Do you think that's all React is capable of?
React can run in both browser and node with one set of code, and can run in iOS and Android systems in the native App posture, which not only has the fast iterative characteristics of web, but also has the native App experience.
This pose is called React-Native.
This is the data of React and React-Native on github, and you can see that React-Native is also quite popular-- because React-Native can maximize the value of React, what is this value-- for business, it means that there is no need to recruit as much manpower as front-end terminal development in order to do the terminal version, and it also means that we have a shortcut to becoming a full-stack engineer.
Students who are familiar with iOS development know that the efficiency of the review of applications on shelves by fruit companies is really hard to complain about, and many teams have already done the next version before the last version is finished. React-Native supports pulling JS from the network, so that iOS applications can iterate as fast as web.
This is the debugging process of react-native.
As a web front-end developer who hasn't written a single sentence of Object-C code, it only took me one day to get started with react-native, and then it took me half a day to make a simple demo page. I can see that react-native is still very productive.
As the name implies, unit testing is the smallest range of testing of each module, which is easy.
Because of the existence of virtual DOM, it is easy for the react code to do the unit test. This is the test case of the above code, and the result can be seen after execution by karma.
The answers to the questions about how to deeply understand the data flow and the principle of events are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.