Home Web Front-end JS Tutorial React high-order component example analysis

React high-order component example analysis

May 26, 2018 am 11:51 AM
react Example parse

This article mainly gives you an in-depth understanding of React high-order components. I hope you will have a clearer understanding of React high-order components.

1. In React, higher-order component (HOC) is an advanced technology for reusing component logic. HOC is not part of the React API. A HOC is a function that takes a component and returns a new component. In React, components are the basic unit of code reuse.

2. In order to explain HOCs, take the following two examples

The CommentList component will render a comments list, and the data in the list comes from the outside.

class CommentList extends React.Component {

  constructor() {

   super();

   this.handleChange = this.handleChange.bind(this);

   this.state = {

    // "DataSource" is some global data source

    comments: DataSource.getComments()

   };

  }

 

  componentDidMount() {

   // Subscribe to changes

   DataSource.addChangeListener(this.handleChange);

  }

 

  componentWillUnmount() {

   // Clean up listener

   DataSource.removeChangeListener(this.handleChange);

  }

 

  handleChange() {

   // Update component state whenever the data source changes

   this.setState({

    comments: DataSource.getComments()

   });

  }

 

  render() {

   return (

    <p>

     {this.state.comments.map((comment) => (

      <Comment comment={comment} key={comment.id} />

     ))}

    </p>

   );

  }

 }
Copy after login

Next is the BlogPost component, which is used to display a blog message

class BlogPost extends React.Component {

  constructor(props) {

   super(props);

   this.handleChange = this.handleChange.bind(this);

   this.state = {

    blogPost: DataSource.getBlogPost(props.id)

   };

  }

 

  componentDidMount() {

   DataSource.addChangeListener(this.handleChange);

  }

 

  componentWillUnmount() {

   DataSource.removeChangeListener(this.handleChange);

  }

 

  handleChange() {

   this.setState({

    blogPost: DataSource.getBlogPost(this.props.id)

   });

  }

 

  render() {

   return <TextBlock text={this.state.blogPost} />;

  }

 }
Copy after login

These two components are different, they call different methods of DataSource, and their output are different, but most of their implementations are the same:

1. After the loading is completed, a change listener is added to the DataSource
2. When the data source changes, inside the listener Call setState
3. After uninstalling, remove the change listener

It is conceivable that in large applications, the same pattern of accessing DataSource and calling setState will happen again and again. We want to abstract this process so that we only define this logic in one place and then share it across multiple components.

Next we write a function that creates a component. This function accepts two parameters, one of which is the component and the other is the function. The withSubscription function is called below

const CommentListWithSubscription = withSubscription(

 CommentList,

 (DataSource) => DataSource.getComments()

);

 

const BlogPostWithSubscription = withSubscription(

 BlogPost,

 (DataSource, props) => DataSource.getBlogPost(props.id)

);
Copy after login

The first parameter passed when calling withSubscription is the wrapped component, and the second parameter is a function, which is used to retrieve data.

When CommentListWithSubscription and BlogPostWithSubscription are rendered, CommentList and BlogPost will accept a prop called data, which stores the data currently retrieved from the DataSource. The withSubscription code is as follows:

// This function takes a component...

function withSubscription(WrappedComponent, selectData) {

 // ...and returns another component...

 return class extends React.Component {

  constructor(props) {

   super(props);

   this.handleChange = this.handleChange.bind(this);

   this.state = {

    data: selectData(DataSource, props)

   };

  }

 

  componentDidMount() {

   // ... that takes care of the subscription...

   DataSource.addChangeListener(this.handleChange);

  }

 

  componentWillUnmount() {

   DataSource.removeChangeListener(this.handleChange);

  }

 

  handleChange() {

   this.setState({

    data: selectData(DataSource, this.props)

   });

  }

 

  render() {

   // ... and renders the wrapped component with the fresh data!

   // Notice that we pass through any additional props

   return <WrappedComponent data={this.state.data} {...this.props} />;

  }

 };

}
Copy after login

HOC does not modify the input component, nor does it use inheritance to reuse its behavior. HOC is just a function. The wrapped component accepts all the props of the container, and also accepts a new prop (data), which is used to render the output of the wrapped component. HOC doesn't care how the data is used or why the data is used, and the wrapped component doesn't care where the data is obtained.

Because withSubscription is just a regular function, you can add any number of parameters. For example, you can make the name of the data prop configurable to further isolate the HOC from the wrapped component.

Either accept a configuration shouldComponentUpdate, or configure the parameters of the data source

There are some things that need to be paid attention to when using high-order components.

1. Do not modify the original component, this is very important

There are the following examples:

function logProps(InputComponent) {

 InputComponent.prototype.componentWillReceiveProps = function(nextProps) {

  console.log(&#39;Current props: &#39;, this.props);

  console.log(&#39;Next props: &#39;, nextProps);

 };

 // The fact that we&#39;re returning the original input is a hint that it has

 // been mutated.

 return InputComponent;

}

 

// EnhancedComponent will log whenever props are received

const EnhancedComponent = logProps(InputComponent);
Copy after login

There are some problems here, 1. The input component cannot be separated from the enhanced component Reuse. 2. If you apply other HOCs to EnhancedComponent, componentWillReceiveProps will also be changed.

This HOC is not applicable to function type components, because function type components do not have a life cycle. Function HOC should use composition instead of modification - by wrapping the input component into a container component.

function logProps(WrappedComponent) {

 return class extends React.Component {

  componentWillReceiveProps(nextProps) {

   console.log(&#39;Current props: &#39;, this.props);

   console.log(&#39;Next props: &#39;, nextProps);

  }

  render() {

   // Wraps the input component in a container, without mutating it. Good!

   return <WrappedComponent {...this.props} />;

  }

 }

}
Copy after login

This new logProps has the same functionality as the old logProps, while the new logProps avoids potential conflicts. The same applies to class type components and function type components.

2. Don’t use HOCs in the render method

React’s diff algorithm uses the identity of the component to decide whether it should update the existing subtree or tear down the old subtree and load a new one , if the component returned from the render method is equal to the previously rendered component (===), then React will update the previously rendered component through the diff algorithm. If not, the previously rendered subtree will be completely unloaded.

render() {

 // A new version of EnhancedComponent is created on every render

 // EnhancedComponent1 !== EnhancedComponent2

 const EnhancedComponent = enhance(MyComponent);

 // That causes the entire subtree to unmount/remount each time!

 return <EnhancedComponent />;

}
Copy after login

Use HOCs outside the component definition so that the resulting component is only created once. In a few cases, you need to apply HOCs dynamically, you should do this in the life cycle function or constructor

3. Static methods must be copied manually

Sometimes in React It is very useful to define static methods on components. When you apply HOCs to a component, although the original component is wrapped in a container component, the returned new component will not have any static methods of the original component.

// Define a static method

WrappedComponent.staticMethod = function() {/*...*/}

// Now apply an HOC

const EnhancedComponent = enhance(WrappedComponent);

 

// The enhanced component has no static method

typeof EnhancedComponent.staticMethod === &#39;undefined&#39; // true
Copy after login

In order for the returned component to have the static methods of the original component, it is necessary to copy the static methods of the original component to the new component inside the function.


function enhance(WrappedComponent) {

 class Enhance extends React.Component {/*...*/}

 // Must know exactly which method(s) to copy :(

  // 你也能够借助第三方工具

 Enhance.staticMethod = WrappedComponent.staticMethod;

 return Enhance;

}
Copy after login

4. The ref on the container component will not be passed to the wrapped component

Although the props on the container component can be easily passed to the wrapped component, But the ref on the container component is not passed to the wrapped component. If you set a ref for a component returned through HOCs, this ref refers to the outermost container component, not the wrapped component.

Related recommendations

React high-order component entry example sharing

How to use Vue high-order component

Use a very simple example to understand the idea of ​​react.js high-order components

The above is the detailed content of React high-order component example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

Comparison of Java libraries for XML parsing: Finding the best solution Comparison of Java libraries for XML parsing: Finding the best solution Mar 09, 2024 am 09:10 AM

Introduction XML (Extensible Markup Language) is a popular format for storing and transmitting data. Parsing XML in Java is a necessary task for many applications, from data exchange to document processing. To parse XML efficiently, developers can use various Java libraries. This article will compare some of the most popular XML parsing libraries, focusing on their features, functionality, and performance to help developers make an informed choice. DOM (Document Object Model) parsing library JavaXMLDOMAPI: a standard DOM implementation provided by Oracle. It provides an object model that allows developers to access and manipulate XML documents. DocumentBuilderFactoryfactory=D

The relationship between the number of Oracle instances and database performance The relationship between the number of Oracle instances and database performance Mar 08, 2024 am 09:27 AM

The relationship between the number of Oracle instances and database performance Oracle database is one of the well-known relational database management systems in the industry and is widely used in enterprise-level data storage and management. In Oracle database, instance is a very important concept. Instance refers to the running environment of Oracle database in memory. Each instance has an independent memory structure and background process, which is used to process user requests and manage database operations. The number of instances has an important impact on the performance and stability of Oracle database.

See all articles