Application of high-level functions and high-level components in react - (below) (case details login authentication and enhanced props)

foreword

The last article introduced the concepts related to higher-order functions. After understanding the idea of ​​higher-order functions, this article will take you to learn about higher-order components. If you haven't studied the previous article, click the link below to view the exciting content:
The use of higher-order functions and higher-order components in react - (Part 1) (the case explains the higher-order functions in detail)

higher order components

A higher-order component is a function that takes a component as a parameter and returns a new component. Higher-order components (HOC) are an advanced technique in React for reusing component logic. HOC itself is not part of the React API, it is a design pattern based on the compositional characteristics of React.

Example of higher order components

Here we still write an example, which is written in the form of components to illustrate, there are three login, logout, and registration:
login:

import React, {
    
     Component } from 'react'
export class Login extends Component {
    
    
    state = {
    
    
        username: ''
    }
    // 模拟使用axios获取useranem,在生命周期中实现
    componentDidMount() {
    
    
        const username = 'admin'
        this.setState({
    
    username: username})
    }
    render() {
    
    
        return (
            <div>
                <h1>Login</h1>
                <p>{
    
    this.state.username}登录了</p>
            </div>
        )
    }
}
export default Login

The contents of logout and registration are the same as above, but the names are different. I will not post the code here. It affects the space.
You can see that there will be repeated parts in these three group prices, such as obtaining username here, so we avoid these components. What about redundant code? We need to write a higher order component to extract the same parts.

Case rewriting

Define the username.js file:
1. Define PropUsername, the parameter WrapComponent inside is a component
2. The state and componentDidMount inside are the same as above, that is, repeat the code
3. Here you need to return the username for external use, so you need to use props for it Pass the value, that is, return return < WrapComponent username={this.state.username} />
4. Finally return this component

import React, {
    
     Component } from 'react'

function PropUsername(WrapComponent) {
    
    
    class NewComponent extends Component {
    
    
        state = {
    
    username: ''}
        componentDidMount() {
    
    
            const username = '超管admin'
            this.setState({
    
    username: username})    
        }
        render() {
    
    
            return <WrapComponent username={
    
    this.state.username} />
        }
    }
    return NewComponent
}

export default PropUsername

The public repeated part has been written as a high-order component, so how to use this component in other places?

The login page is rewritten as follows (logout and registration are the same):
1. The public part above is written as a high-order component, and props are used to pass values, so here use this.props.username to receive the value
2. Rewrite when it is finally thrown Successfully throw PropUsername(Login) and pass in the component login

import React, {
    
     Component } from 'react'
import PropUsername from './04username'

export class Login extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <h1>Login</h1>
                <p>{
    
    this.props.username}登录了</p>
            </div>
        )
    }
}

export default PropUsername(Login)

Login authentication

What is login authentication? See the following example:

class Login extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <h1>登录页面</h1>
            </div>
        )
    }
}

class Admin extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <h1>管理员页面</h1>
            </div>
        )
    }
}

If there is a login page and an administrator page, and there is an islogin attribute in the state, we need to use the islogin attribute to determine which page to display. What should we do? Most people should think that it is written in ternary expressions. How to implement it if higher-order components are used here?

Looking at the following code, the extraction is a high-level component:
1. Define the AuthComponent function, and the received parameter Component is a component
2. Define NewComp, and then judge by props, get isLogin from props, and return the called Component if it is true. , and pass in props. If false, return < Login/>
3. Finally, return NewComp. Define AuthAdmin outside, and pass admin into the AuthComponent function

function AuthComponent(Component) {
    
    
    const NewComp = (props) => {
    
    
        const {
    
    isLogin} = props
        // 如果为true展示Admin组件,反之展示Login组件
        if (isLogin) {
    
    
            return <Component {
    
    ...props}/>
        } else {
    
    
            return <Login/>
        }
    }
    return NewComp
}
const AuthAdmin = AuthComponent(Admin)

Use the above higher-order functions:
1. Use the AuthAdmin component defined above directly, and isLogin passes in the value of this.state.isLogin

class App extends Component {
    
    
    state = {
    
    isLogin: true}
    render() {
    
    
        return (
            <div>
                <h1>主页面</h1>
                <AuthAdmin isLogin={
    
    this.state.isLogin}/>
                <button onClick={
    
    this.click}>{
    
    this.state.isLogin ? '退出' : '请登录'}</button>
            </div>
        )
    }
    click = () => {
    
    
        this.setState({
    
    isLogin: !this.state.isLogin})
    }
}

export default App

Check the effect:
insert image description here

Enhanced props

Passing one more attribute to each prop does not matter, but if there are too many components, it is not suitable to pass one by one, and the way of adding attributes directly to components will change the original code structure, we can use higher order Components, hijack each component before use, and add a new property to each component.

See the following example:

import React, {
    
     Component } from 'react'

class People extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <h1>People Page</h1>
                <p>我的名字是:{
    
    this.props.name}</p>
                <p>我的年龄是:{
    
    this.props.age}</p>
                <p>我的兴趣是:{
    
    this.props.inst}</p>
                <p>我的爱好是:{
    
    this.props.hobby}</p>
            </div>
        )
    }
}

class Boy extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <h1>Boy Page</h1>
                <p>我的名字是:{
    
    this.props.name}</p>
                <p>我的年龄是:{
    
    this.props.age}</p>
                <p>我的兴趣是:{
    
    this.props.inst}</p>
                <p>我的爱好是:{
    
    this.props.hobby}</p>
            </div>
        )
    }
}
const PropsComponent = (Component) => {
    
    
    // 返回一个函数式组件
    const newComponent = (props) => {
    
    
        return <Component {
    
    ...props} inst="打代码" hobby="打游戏" />
    }
    return newComponent
}

const PeopleProps = PropsComponent(People)
const BoyProps = PropsComponent(Boy)

export class App extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <PeopleProps  name="张三" age="16"/>
                <BoyProps  name="李四" age="12"/>
            </div>
        )
    }
}

export default App

Here, the high-level component PropsComponent is directly defined for display, and the same props properties are directly written in the high-level component price: < Component {…props} inst=“playing code” hobby=”playing games” />, different properties , it can be directly displayed in the final component using props to pass the value.
insert image description here

Therefore, the props enhancement of higher-order components can be used more flexibly.

Well, this is the end of the content of this article. This article mainly takes you to learn the use of high-level components through cases, as well as the knowledge related to implementing login authentication and enhancing props in high-level components. I hope it can help you. You guys~
If it is helpful to you, please like, follow and support~ The follow-up will bring you more exciting content

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123563110