The article directories
-
- An overview of the
- Component life cycle
-
- 1.1 Creation Phase
- 1.2 Instantiation phase
- 1.3 Run (Update) Phase
- 1.4 Destruction Stage
- Second, detailed introduction of life cycle function
-
- constructor
- getDefaultProps
- componentWillMount
- render
- componentDidMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
- Complete sample
- Four,
An overview of the
The so-called life cycle is the state that an object goes through from the beginning of generation to the end of death. Understanding the life cycle is the key to rational development. The life cycle of RN components is sorted as follows:
As shown, the component life cycle can be roughly divided into three phases:
- The first stage: the component is drawn for the first time, in the dotted box above, where the component is loaded and initialized.
- The second stage: the component is in the operation and interaction stage, as shown in the lower left corner of the dotted box. In this stage, the component can handle user interaction or receive events to update the interface.
- Phase 3: The component uninstallation and death phase, shown in the lower right corner of the dotted box, where some component cleaning is done.
Component life cycle
The component life cycle is typically divided into four phases: create, instantiate, run (update), and destroy. Each stage is described below.
1.1 Creation Phase
This phase occurs when the component class is created and initializes the component’s property types and default properties. Fixed content is usually placed in this process for initialization and assignment. Static members are used uniformly in ES6.
static defaultProps = {
autoPlay: false,
maxLoop: 10};Copy the code
1.2 Instantiation phase
This phase occurs mainly when the component class is instantiated, which is when the component class is invoked. This phase triggers a series of processes in the following order of execution:
constructor
Constructor, which initializes some state of the component.componentWillMount
: Ready to load the component, you can do some business initialization here, or set the component state.render
: required to generate the pageDOM
Structure, and returns the structure.componentDidMount
: executes after the component has been successfully loaded and rendered. Generally, network requests and other data loading operations are placed here to ensure that they do not occurUI
Error on.
1.3 Run (Update) Phase
This stage mainly occurs after user operations or when the parent component is updated. At this time, the corresponding page structure will be adjusted according to user operations. This phase also triggers a series of processes, executed in the following order:
componentWillReceiveProps
: When the component receives a newprops
, the function is triggered. In this function, you can usually callthis.setState
Method to complete the pairstate
Modifications.shouldComponentUpdate
: This method is used to intercept newprops
或state
, and then make the final decision whether to update the component based on the preset judgment logic.componentWillUpdate
: returns when the above method interceptstrue
You can then do some pre-update operations in this method.render
: According to a series ofdiff
Algorithm that generates the required updateVirtual DOM
The data. (Note: inrender
It is best to do only the combination of data and template, should not be carried outstate
The logic is modified so that the component structure is clearer.componentDidUpdate
: This method has been synchronized to the component’s updateDOM
Is triggered after, usually in this methodDOM
Operation.
1.4 Destruction Stage
This phase is triggered primarily when a component dies.
componentWillUnmount
: called when a component is about to be removed from the interface. You can do some related cleanup in this function, such as canceling timers, network requests, and so on.
Second, detailed introduction of life cycle function
The following details each callback function in the lifecycle.
constructor
(1) Function prototype
constructor(props)
Copy the code
It is a component constructor. Its first statement must be super(props). The constructor is called first and only once before the component is loaded.
This is where the state machine variables are defined.
getDefaultProps
Before the component is created, getDefaultProps() is called once globally. Strictly speaking, this is not part of the component lifecycle. After the component is created and loaded, the first call to getInitialState() initializes the state of the component.
componentWillMount
Then, ready to load the component, calls componentWillMount() with the following prototype:
void componentWillMount(a)
Copy the code
This function is called after the component is created and the state is initialized, but before the first render() is drawn.
(2) Basic introduction
- This function is executed only once during the life of the component.
- This function takes no arguments and does not require any return value.
- It is used in the initial rendering (
render
Function isReact Native
The framework call is executed, and when it is finished,render
The function will be immediately destroyedReact Native
The framework call executes. Note: if called in this functionsetstate
The function changes the value of some state machine variables,React Native
Instead of performing a render operation, the framework waits for the function to complete before performing an initial render.- If the child component also has
componentWillMount
Function, which will be in the parent componentcomponentWillMount
The function is then called.
If we need to read data from local storage for display purposes, this is a good time to do so. You can do some business initialization here, and you can also set the component state.
render
(1) Function prototype
render()
Copy the code
(2) Basic introduction render is a component must have method, used for interface rendering. This function takes no arguments and returns JSX or some other component to form the DOM.
Note: Only one top-level element can be returned.
componentDidMount
After the component is first drawn, componentDidMount() is called to inform you that the component has been loaded. The function prototype is as follows:
void componentDidMount(a)
Copy the code
When this function is called, the virtual DOM has been built and you can start retrieving elements or subcomponents from the function. 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 timing setTimeout or setInterval, or making network requests. This function is also called only once. After this function, it enters a stable state, waiting for the event to fire.
(2) Basic introduction
- This function is executed only once during the life of the component.
- This function takes no arguments and does not require any return value.
- It is called immediately after the initial render execution is complete. After this point in a component’s life cycle, developers can access and manipulate any child component through its references.
- If the child component also has
componentDidMount
Function, which will be in the parent componentcomponentDidMount
Function is called before.
If a React Native application needs to fetch data from the network after the application starts up and displays the initial interface, it’s a good idea to put the code to fetch data from the network in this function.
componentWillReceiveProps
If the component received a new attribute (props), is called componentWillReceiveProps (), its prototype is as follows:
void componentWillReceiveProps( object nextProps )
Copy the code
The input parameter nextProps is the property to be set. The old property can still be obtained via this.props. Within this callback, the component state can be updated by calling this.setState(), depending on the property change, where updating the state is safe and does not trigger additional render() calls. As follows:
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
Copy the code
(2) Basic introduction
- The initial rendering of the component is completed when the component receives the new
props
, the function will be called.- This function does not require a return value. To receive a
object
Parameters,object
Is the newprops
.- If the new
props
Causes the interface to re-render, and this function will be executed before rendering. In this function, the oldprops
Can be achieved bythis.props
Visit, newprops
In the incomingobject
In the.- If I call it in this function
this.setState
The function changes the value of some state machine variables,React Native
Instead of rendering these state machine variables, the framework waitscomponentWillReceiveProps
Render together after the function completes execution.
Note: when the React Native be rendered for the first time, componentWillReceiveProps function will not be triggered, this mechanism is designed deliberately.
shouldComponentUpdate
The call shouldComponentUpdate(…) is triggered when the component receives a new property and a state change. , the function prototype is as follows:
boolean shouldComponentUpdate( object nextProps, object nextState )
Copy the code
NextProps input parameters and the above componentWillReceiveProps function, nextState presentation components will update the status value. The return value of this function determines whether the component needs to be updated, and if true means it needs to be updated, the update process continues. If no, the system does not update the data and enters the waiting state directly.
By default, this function always returns true to ensure that the UI updates synchronously when data changes. In large projects, you can override this function yourself to determine whether the UI needs to be updated by checking the properties and state before and after the change, effectively improving application performance.
(2) Basic introduction
- After the initial rendering of the component completes, when the component receives a new one
state
orprops
This function will be called when.- The function accepts two
object
Parameter, the first of which is newprops
The second one is newstate
.- The function needs to return a Boolean value that tells
React Native
Whether the framework needs to re-render this component for this change. The default returntrue
. If this function returnsfalse
.React Native
This component will not be re-rendered and, accordingly, the component’scomponentWillUpdate
和componentDidUpdate
The function will not be called.
This function is often used to prevent unnecessary re-rendering and improve React Native application performance. For example, we can compare the old and new versions of state and props to see if we need to re-render. Here is a simple usage example:
shouldComponentUpdate(nextProps, nextState) {
if(this.state.inputedNum.length < 3) return false;
return true;
}
Copy the code
componentWillUpdate
If the component state or property changes and the above shouldComponentUpdate(…) Returns true, the quasi-update component begins, and calls componentWillUpdate(), which has the following function prototype:
void componentWillUpdate( object nextProps, object nextState )
Copy the code
The input parameter is the same as shouldComponentUpdate, and in this callback, you can do something you want to do before updating the interface. It is important to note that you cannot use this.setState to change the state in this function. This function call sets the nextProps and nextState to this.props and this.state, respectively. Following this function, render() is called to update the interface.
(2) Basic introduction
- After the initial rendering of the component is executed,
React Native
The framework calls this function before rerendering the component.- This function does not need to return values; it accepts two
object
Parameter, the first of which is newprops
The second one is newstate
.- It is possible to do some preparatory work in this function for the rerendering that is about to take place, but it cannot be passed in this function
this.setState
Change the value of the state machine variable again. If a change is needed, it is incomponentWillReceiveProps
Delta function.
componentDidUpdate
After calling render() to update the finished interface, componentDidUpdate() is called to be notified, with the following function prototype:
void componentDidUpdate( object prevProps, object prevState )
Copy the code
At this point, the properties and state are updated, and the input arguments to this function become prevProps and prevState.
Basic introduction
- After the initial rendering of the component is executed,
React Native
The framework calls this function when it has finished rerendering the component.- This function does not need to return values; it accepts two
object
Parameter, the first of which is pre-renderprops
The second one is before renderingstate
.
componentWillUnmount
When a component is to be removed from the interface, componentWillUnmount() is called, with the following function prototype:
void componentWillUnmount(a)
Copy the code
In this function, you can do component-related cleanup, such as canceling timers, network requests, and so on.
(2) Basic introduction
- This function is executed before the component is unloaded.
- This function takes no arguments and does not require a return value.
If a component has requested resources or subscribed to messages, it needs to release resources and unsubscribe from this function.
Complete sample
The following is a simple text display component to demonstrate the operation flow of each link of the component. It also lists all the methods that are triggered throughout the life cycle of the component.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
TextInput,
View,
Text,
Clipboard
} from 'react-native';
export default class Main extends Component {
// constructor
constructor(props) {
super(props);
console.log("constructor");
// Initializes the state value
this.state = {message: "Welcome to hangge.com"}}// Ready to load the component
componentWillMount() {
console.log("componentWillMount");
}
// Render the interface
render() {
console.log("render");
return (
<View style={styles.container}>
<Text style={styles.info}>
{this.state.message}
</Text>
</View>
);
}
// The component is loaded successfully and rendered
componentDidMount() {
console.log("componentDidMount");
}
Emitted when the component receives new props
componentWillReceiveProps(nextProps) {
console.log("componentWillReceiveProps");
}
// Determine whether the component needs to be updated
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate");
}
// is called before the component is re-rendered
componentWillUpdate(nextProps, nextState) {
console.log("componentWillUpdate");
}
// will be called after the component is re-rendered
componentDidUpdate(prevProps, prevState) {
console.log("componentDidUpdate");
}
// is called before the component is uninstalled
componentWillUnmount() {
console.log("componentWillUnmount"); }}const styles = StyleSheet.create({
container:{
flex:1,
marginTop:40,
alignItems:'center',
},
info:{
fontSize:20,}}); AppRegistry.registerComponent('HelloWorld', () => Main);
Copy the code
The console output is as follows (because the sample does not update the state and does not destroy the component. So there are no later two stages) :
Four,
At this point, the complete life of an RN component is described. If you look back at the previous figure, it becomes clear that the lifecycle callback functions can be summarized in the following table: