In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "analyzing the life cycle of components in React". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "analyze the life cycle of components in React".
Initialization
Executes during the component initialization phase
00001. Constructor
00002. Static getDerivedStateFromProps ()
00003. ComponentWillMount () / UNSAFE_componentWillMount ()
00004. Render ()
00005. ComponentDidMount ()
Update phase
Changes to props or state may cause updates to the component, and the following methods are called during component re-rendering:
00001. ComponentWillReceiveProps () / UNSAFE_componentWillReceiveProps ()
00002. Static getDerivedStateFromProps ()
00003. ShouldComponentUpdate ()
00004. ComponentWillUpdate () / UNSAFE_componentWillUpdate ()
00005. Render ()
00006. GetSnapshotBeforeUpdate ()
00007. ComponentDidUpdate ()
Unloading Pha
00001. ComponentWillUnmount ()
Error handling
00001. ComponentDidCatch ()
Detailed explanation of each life cycle 1.constructor (props)
The constructor of the React component is called before mounting. When implementing the React.Component constructor, you need to call super (props) before adding anything else to bind the props from the parent component to this class, which you will get using this.props.
It is officially advised not to introduce any code with side effects and subscription features in constructor, which should use componentDidMount ().
Initialization should be done in constructor, such as initializing state and binding event handlers to class instances, but do not use setState () either. If there is no need to initialize state or bind methods, you do not need to construct constructor or replace the component with pure functional writing.
Of course, you can also use props to initialize state. Modifying state later will not cause any changes to props, but it is still recommended that you promote the state to the parent component, or use redux for unified state management.
Constructor (props) {
Super (props)
This.state = {
IsLiked: props.isLiked
};}
2.static getDerivedStateFromProps (nextProps, prevState)
GetDerivedStateFromProps is added after react16.3 and is called after the component is instantiated and the new props is accepted. He must return an object to update the status, or return null to indicate that the new props does not require any state updates.
This method is also triggered if it is due to a props change in the parent component, resulting in re-rendering.
Calling steState () does not trigger getDerivedStateFromProps ().
Before, constructor+componentWillRecieveProps was used to accomplish the same function here.
3. ComponentWillMount () / UNSAFE_componentWillMount ()
ComponentWillMount () will be deprecated in future versions of React (officially 17.0). UNSAFE_componentWillMount () is called before the component is mounted, and calling setState () in this method does not work because it is called before render ().
To avoid side effects and other subscriptions, officials recommend using componentDidMount () instead. This method is the only method used on server rendering. Because this method is called before rendering, it is also the only place where you can modify the state synchronously.
4.render ()
The render () method is required. When he is called, he evaluates this.props and this.state and returns one of the following types:
00001. React element. Created by jsx, it can be either a dom element or a user-defined component.
00002. A string or number. They will be rendered into dom as text nodes.
00003. Portals . The new solution proposed in react 16 allows components to be mounted anywhere in the DOM tree away from the parent component level.
00004. Null, nothing is rendered
00005. Boolean value. It doesn't render anything either.
When null,false,ReactDOM.findDOMNode (this) is returned, null will be returned and nothing will be rendered.
The render () method must be a pure function, it should not change the state, nor can it interact directly with the browser, but should put events in other lifecycle functions. If shouldComponentUpdate () returns false,render (), it will not be called.
5. ComponentDidMount
ComponentDidMount is called immediately after the component is assembled. Initialization so that the DOM node should go so far.
Ajax requests are usually made here
If you want to initialize a third-party dom library, initialize it here as well. Only here can we get the real dom.
6.componentWillReceiveProps () / UNSAFE_componentWillReceiveProps (nextProps)
The official recommendation is to use the getDerivedStateFromProps function instead of componentWillReceiveProps. When the component is mounted, it will be called when a new props is received. If you need to update state in response to changes in props, you can compare this.props to nextProps and use this.setState () in this method.
If the parent component causes the component to re-render, this method will be called even if the props has not changed.
React does not call this method when the component initializes the props. Calling this.setState will not trigger either.
7.shouldComponentUpdate (nextProps, nextState)
Call shouldComponentUpdate to let React know whether the output of the component is affected by state and props. By default, each state change is re-rendered, and this default behavior should be maintained in most cases.
ShouldComponentUpdate is called before rendering a new props or state. The default is true. This method will not be called during initialization, nor will it be called when forceUpdate (). Returning to false does not prevent sub-components from re-rendering when state changes.
If shouldComponentUpdate () returns false,componentWillUpdate,render and componentDidUpdate, it will not be called.
Officials do not recommend doing deep queries in shouldComponentUpdate () or using JSON.stringify (), which is very inefficient and compromises performance.
8.UNSAFE_componentWillUpdate (nextProps, nextState)
When rendering a new state or props, UNSAFE_componentWillUpdate is called as an opportunity to prepare before the update occurs. This method will not be called during initialization.
You cannot use this.setState () here, nor can you do anything that triggers a view update. If you need to update state or props, call getDerivedStateFromProps.
9.getSnapshotBeforeUpdate ()
The output after react render () is called before it is rendered to DOM. It enables your components to capture current values (such as scrolling positions) before they are potentially changed. Any value returned by this life cycle will be passed to componentDidUpdate () as an argument.
10.componentDidUpdate (prevProps, prevState, snapshot)
Call componentDidUpdate () immediately after the update occurs. This method is not used for initial rendering. When the component is updated, use this as an opportunity to manipulate the DOM. As long as you compare the current props with the previous props (for example, if the props has not changed, you may not need a network request), this is also a good place to make a network request.
If the component implements the getSnapshotBeforeUpdate () life cycle, the value it returns is passed to componentDidUpdate () as the third "snapshot" parameter. Otherwise, this parameter is undefined.
11.componentWillUnmount ()
Called immediately before the component is uninstalled and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any snooping created in componentDidMount.
12.componentDidCatch (error, info)
The error boundary is the React component, where you can catch JavaScript errors anywhere in its subcomponent tree, log them, and display a fallback UI instead of a crashed component tree. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors under the entire tree.
If the class component defines this lifecycle method, it becomes an error boundary. Calling setState () in it allows you to catch unhandled JavaScript errors in the tree below and display a backup UI. You can only use error boundaries to recover from unexpected exceptions; do not try to use them to control the process.
Error boundaries only catch errors in the following components in the tree. The error boundary itself cannot catch the error.
PureComponent
If the new attribute or the changed state is the same as the original attribute or the original state in PureComponnet, it will not be re-render. You can also use shouldComponentUpdate in it. The final decision on whether to re-render depends on the return value of shouldComponentUpdate.
Import React, {PureComponent} from 'react'
Class YourComponent extends PureComponent {
……
}
Ref
The ref property provided by React, expressed as a reference to the real instance of the component, is actually the instance of the component returned by ReactDOM.render (), and the ref can be mounted on the component or on the dom element.
A ref attached to a component (a component declared by class) represents a reference to the component instance. You cannot use the ref property on functional components because they have no instances:
When mounted on a dom element, it represents a specific dom element node.
In the latest version of React, to use ref, you need to use the React.createRef method to form a ref.
Import React, {Component, createRef} from 'react'import ReactDOM from' react-dom'class App extends Component {
Constructor () {
Super ()
/ / create inputRef this.inputRef=createRef ()
}
ComponentDidMount () {
Console.log (this.inputRef.current) / /}
Render () {
Return (
{/ * Associate ref and dom * /}
)
}} ReactDOM.render (
Document.getElementById ('root'))
React Hooks
React Hooks is a new feature in the React 16.7.0-alpha version. With React Hooks, the state and component lifecycle of classes components can also be used in react functional components. Learn about React Hooks through the following examples.
State Hook
/ / useState is a method provided by the react package import React, {useState} from "react"; import ReactDOM from "react-dom"; const Counter = () = > {
The / / useState method can have its own state for our function component, which receives a value for the initial state and returns a pair of variables. Here we set the initial value of the counter to 0, and the methods all start with set const [count, setCount] = useState (0)
Return (
You clicked {count} times.
SetCount (count + 1)} > Click
);}; const rootElement = document.getElementById ("root"); ReactDOM.render (, rootElement)
Effect Hook
/ / useState is a method provided by the react package import React, {useState, useEffect} from "react"; import ReactDOM from "react-dom"; const Counter = () = > {
The / / useState method can have its own state for our function component, which receives a value for the initial state and returns a pair of variables. Here we set the initial value of the counter to 0, and the methods all start with set const [count, setCount] = useState (0)
/ / similar to componentDidMount or componentDidUpdate: useEffect (() = > {
/ / change the title of the page, you can also do other monitoring document.title = `you clicked on ${count} `
});
Return (
You clicked {count} times.
SetCount (count + 1)} > Click
);}; const rootElement = document.getElementById ("root"); ReactDOM.render (, rootElement)
Rules of React Hooks
Hooks can only be called at the top level. Do not call Hook in loops, conditions, or nested functions.
Do not call Hook from regular JavaScript functions. Hooks is called only on React functional components.
Custom hooks can be explained by choice.
React built-in hooks api
Basic Hooks
UseState
UseEffect
UseContext
Additional Hooks
UseReducer
UseCallback
UseMemo
UseRef
UseImperativeHandle
UseLayoutEffect
UseDebugValue
Thank you for your reading, the above is the content of "analyzing the life cycle of components in React". After the study of this article, I believe you have a deeper understanding of analyzing the life cycle of components in React, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.