Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use React function components and class components

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "React function components and class components", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "React function components and class components how to use" article.

First, the problem of class components

Since the introduction of Hooks by React, functional component writing has become popular, while class component writing has been declining. What causes it? I think there are three reasons:

First, because of the problems brought about by this:

There is a famous case that shows the problems caused by the class component this. Let me reproduce this case by localizing it.

Import React from "react" const ProfileFunction: React.FC = (props) = > {const showMessage = () = > {alert (`You ordered "${props.goods}"! `)} const handleClick = () = > {setTimeout (showMessage, 3 * 1000)} return (purchase)} class ProfileClass extends React.Component

< { goods: string }, // props 类型 {} // state 类型>

{showMessage = () = > {alert (`You ordered "${this.props.goods}"! `)} handleClick = () = > {setTimeout (this.showMessage, 3 * 1000)} render () {return purchase}} export default class App extends React.Component {state = {goods: 'Apple',} Render () {return (please choose: this.setState ({goods: e.target.value})} > Apple Banana Watermelon {this.state.goods}

(function)

(class)

)}}

Here is an online case. Interested friends can experience this case online.

Problem description

Function component: when the user selects Apple, clicks to buy, and then switches to browse bananas, prompting the information feedback that the user placed the order is Apple.

Class components: when users select Apple, click to buy, and then switch to browse watermelons, prompting information feedback that the user orders are watermelons!

Problem analysis

At a glance, the code of both the function component and the class component returns a button that pops up an alert prompting the user to place an order after 3 seconds (simulating network delay). Why are the results inconsistent? The parameter props itself is immutable, and the showMessage in the function component still gets the original props.goods after a 3-second delay. However, the this of the instance in the class component is variable. When the showMessage in the class component goes to get the this.props.goods after a 3-second delay, the value obtained is not the original value because the this has changed.

Second, the amount of code of class components is more than that of function components:

As can be seen from the above case, there is less code for functional components of the same function than for class components.

Third, the class components are too bloated and difficult to split:

The biggest difference between class components and function components is the difference in code thinking. Class components are object-oriented programming thinking, and function components are process-oriented programming thinking. The design idea of React is more about combination than inheritance. Heavy use of inheritance in a class component can make the component overweight and difficult to split.

Second, the problem of function components

Functional components used to be called stateless components because state cannot be stored inside functional components. Since react officially launched all kinds of hooks, functional components have become more and more popular. React officially announced that more hooks will be released in the future to implement the functionality of all class components, but this flag has been around for a long time and has not been implemented yet. Let's take an inventory of the hooks corresponding to the method of the class component and the function component in the order of life cycle.

Mounting phase: getDerviedStateFromProps VS none

This method is used to update the props based on the props after the state is passed in.

You can also write code in the function component to update the state based on props, but doing so will result in repeated rendering. If you encounter a situation where you need to update state based on props, you should consider doing a status promotion. If you find that you have to update the state according to props and cannot improve the state in a component, then the component should be written as a classed component, not a functional component.

Mounting phase: UNSAFE_componentWillMount VS none

This method is used to handle some logic before the component is mounted, but it is easy to cause repeated calls in asynchronous rendering mode, which has been officially marked as obsolete by react.

Function components can ignore this method.

Mounting phase: componentDidMount VS useEffect

This method is used to perform side effects after the component is mounted, such as initiating a network request, setting a timer, creating a subscription, and so on.

The function component has useEffect.

Render:

Returns the content to be rendered in the render method of the class component. There can be no side effects and setState in render!

The return of the function component has the same return effect as the render method of the class component.

Life cycle, update phase: UNSAFE_componentWillRerciveProps VS none

This method works just like getDerviedStateFromProps, dealing with some logic before the component is mounted, but the react official has marked it as obsolete.

Function components can ignore this method.

Life cycle, update phase: getDerviedStateFromProps VS none

Same as the method of the same name in the mount phase.

Life cycle, update phase: shouldComponentUpdate VS memo, useMemo, useCallback

This method returns true to indicate that it needs to be updated, and false to indicate that it does not need to be updated. You can add judgment conditions here to optimize the performance, and the principle of PureComponent implementation is the same.

There are many hooks corresponding to function components, such as memo, useMemo and useCallback, which can also be optimized.

Life cycle, update phase: UNSAFE_componentWillUpdate VS none

This method used to do something before the component was re-rendered, which has been officially marked as obsolete by react.

Function components can ignore this method.

Render:

It's the same as the mount phase.

Life cycle, update phase: getSnapshotBeforeUpdate VS none

This method is called before the last rendered output (submitted to the DOM node). It enables the component to capture some information (such as scrolling position, etc.) from the DOM before the change occurs. Any return value from this lifecycle method is passed to componentDidUpdate () as a parameter. This usage is not common, but it may appear in UI processing, such as chat threads that deal with scrolling locations in a special way.

The function component does not have a hooks for this method.

Life cycle, update phase: componentDidUpdate VS none

This method is called immediately after the component is updated, but not for the first rendering. When the component is updated, you can operate on the DOM here. Note: use setState carefully in this method. If you want to use it, you must wrap it in a conditional statement.

The function component does not have the hooks corresponding to this method, because the React itself is designed to reduce the direct operation of DOM. There are few scenarios in React where direct operation of DOM except useRef is possible. It is not a problem for function components to have no hooks corresponding to this method.

Life cycle, uninstall phase: componentWillUnmount VS useEffect

This method is called directly before the component is unloaded and destroyed. Perform necessary cleanup operations in this method, such as clearing timers, canceling network requests, or clearing subscriptions, and so on.

The function component has useEffect.

Other, error boundary: componentDidCatch, static getDerivedStateFromError VS none

When either or both of the two lifecycle methods, static getDerivedStateFromError or componentDidCatch, are defined in the class component, it becomes an error boundary. When an error is thrown, use static getDerivedStateFromError to render the alternate UI and componentDidCatch to print the error message.

Hooks with no error boundary for function components

The above is about the content of this article on "how to use React function components and class components". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report