react basics Day03-life cycle & render props mode & high-order components & principles revealed

Component life cycle (★★★)

Target

  • Name the hook function corresponding to the component life cycle
  • Timing of hook function call

Overview

Significance: The life cycle of a component helps to understand how the component operates, complete more complex component functions, analyze the causes of component errors, etc.

The life cycle of a component: the process from when a component is created to when it is mounted and run on the page, to when it is uninstalled when the component is no longer available

Each stage of the life cycle is always accompanied by some method calls. These methods are the hook functions of the life cycle.

The role of the constructor: provides developers with a practical way to operate components at different stages

life cycle stage

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-mlGHJXtd-1673683573526) (images/lifecycle.png)]

When creating (mounting phase)

  • Execution time: when the component is created (when the page is loaded)
  • Execution order

Insert image description here

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Z2y5ynQK-1673683573530) (images/when created-the role of the function.png)]

When updating

Execution time:setState()、 forceUpdate()、 组件接收到新的props

Note: If any of the above three changes, the component will be re-rendered.

Execution order:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-s394iLvV-1673683573531) (images/update.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-tCD4Zr6d-1673683573531) (images/update-function.png)]

When uninstalling

Execution timing: The component disappears from the page

Function: Used for cleaning operations

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-NSS9hE2B-1673683573532) (images/when uninstalling.png)]

Uncommonly used hook functions

Old version of life cycle hook function

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-oCADQsAZ-1673683573532) (images/old version life cycle function.png)]

The new version of complete life can play chess hook function

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Fgwd9VHv-1673683573532) (images/new version life cycle function.png)]

getDerivedStateFromProps()
  • getDerivedStateFromPropsWill be called before calling the render method, and will be called during initial mount and subsequent updates. It should return an object to update state, if null is returned nothing is updated
  • Regardless of the reason, this method will be triggered before each render
shouldComponentUpdate()
  • Based on shouldComponentUpdate()the return value of , determine whether the output of the React component is affected by changes in the current state or props. The default behavior is that the component will be re-rendered every time the state changes.
  • When props or state changes, shouldComponentUpdate()it will be called before rendering is executed. The return value defaults to true
getSnapshotBeforeUpdate()
  • getSnapshotBeforeUpdate()Called before the last rendered output (submitted to the DOM node). It enables the component to capture some information (for example, scroll position) from the DOM before it changes. Any return values ​​from this lifecycle will be passed as arguments tocomponentDidUpdate()
  • This usage is uncommon, but it may occur in UI processing, such as chat threads that need to handle scroll position in a special way, etc.

render-props mode (★★★)

Target

  • Know what the render-props pattern does
  • Be able to tell the steps for using render-props

Overview of React component reuse

  • Thinking: What should be done if some functions of two components are similar or identical?
  • Solution: Reuse similar functions
  • Reuse what?
    • state
    • How to operate state
  • Two ways:
    • render props mode
    • Higher Order Components (HOC)
  • Note: These two methods are not new APIs, but fixed patterns evolved using React’s own unique coding skills.

Idea analysis

  • Idea: Encapsulate the state to be reused and the methods for operating the state into a component

  • How to get the reused state in this component

    • When using a component, add a prop whose value is a function and obtain it through the function parameters.

      [The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-jV7FGNEE-1673683573533) (images/render-props-01.png)]

  • How to render to arbitrary UI

    • Use the return value of this function as the UI content to be rendered

      [The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-HfMZLuLf-1673683573533) (images/render-props-02.png)]

Steps for usage

  • Create a Mouse component and provide reusable logic code in the component
  • Expose the state to be reused as a parameter of the props.render(state) method to the outside of the component
  • Use the return value of props.render() as the content to render

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-N354QpSG-1673683573534) (images/render-props mode-01.png)]

Example demo
class Mouse extends React.Component {
    // 鼠标位置状态
    state = {
        x: 0,
        y: 0
    }

    // 监听鼠标移动事件
    componentDidMount(){
        window.addEventListener('mousemove',this.handleMouseMove)
    }
    handleMouseMove = e => {
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }
    render(){
        // 向外界提供当前子组件里面的数据
        return this.props.render(this.state)
    }
}
class App extends React.Component {
    render() {
        return (
            <div>
                App
                <Mouse render={mouse => {
                    return <p>X{mouse.x}Y{mouse.y}</p>
                }}/>
            </div>
        )
    }
}
ReactDOM.render(<App />,document.getElementById('root'))

children instead of render attribute

  • Note: It is not necessary to use a prop named render if the mode is called render props. In fact, you can use a prop with any name.
  • The technique of treating a prop as a function and telling the component what to render is called: render props pattern
  • Recommendation: Use children instead of the render attribute

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-YbIbsL9l-1673683573534) (images/render-props-children mode.png)]

Optimize code

  • It is recommended to add props verification to render props mode

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Q0EzGgtW-1673683573535) (images/optimization-add verification.png)]

Insert image description here

High-end components (★★★)

Target

  • Know the role of higher-order components
  • Able to explain high-level usage steps

Overview

  • Purpose: To achieve state logic reuse
  • Use packaging mode
  • Mobile: Get protection features
  • Mobile phone case: provides protection function
  • High-end components are equivalent to mobile phone cases, which enhance the functionality of components by packaging them

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-1f1SU3TE-1673683573536) (images/mobile phone case.png)]

Idea analysis

  • Higher-order component (HOC, Higher-Order Component) is a function that receives the component to be packaged and returns the enhanced component

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-6GeGTHxY-1673683573536) (images/High-order Components-Function.png)]

  • A class component is created inside the higher-order component, which provides reused state logic code and passes the reused state to the packaged component through prop.WrappedComponent

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-uRqz7tr2-1673683573537) (images/High-order Component-Class Component Internal Implementation.png)]

Steps for usage

  • Create a function with a name convention starting with with
  • Specify function parameters, parameters should start with a capital letter
  • Create a class component inside the function, provide reusable state logic code, and return
  • In this component, render the parameter component and pass the state to the parameter component through prop
  • Call the high-order component, pass in the component to be enhanced, get the enhanced component through the return value, and render it to the page

wrapper function

// 定义一个函数,在函数内部创建一个相应类组件
function withMouse(WrappedComponent) {
    // 该组件提供复用状态逻辑
    class Mouse extends React.Component {
        state = {
            x: 0,
            y: 0
        }
        // 事件的处理函数
        handleMouseMove = (e) => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }
        // 当组件挂载的时候进行事件绑定
        componentDidMount() {
            window.addEventListener('mousemove', this.handleMouseMove)
        }
        // 当组件移除时候解绑事件
        componentWillUnmount() {
            window.removeEventListener('mousemove', this.handleMouseMove)
        }
        render() {
            // 在render函数里面返回传递过来的组件,把当前组件的状态设置进去
            return <WrappedComponent {...this.state} />
        }
    }
    return Mouse
}

Which component needs to be enhanced? Just call withMousethis function and set the returned value to the parent component.

function Position(props) {
    return (
        <p>
            X:{props.x}
            Y:{props.y}
        </p>
    )
}
// 把position 组件来进行包装
let MousePosition = withMouse(Position)

class App extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        return (
            <div>
                高阶组件
                <MousePosition></MousePosition>
            </div>
        )
    }
}

set updisplayName

  • Problems with using higher-order components: getting two components with the same name
  • Reason: By default, React uses the component name asdisplayName
  • Solution: Set for high-order components displayNameto facilitate distinguishing different components during debugging
  • displayName的作用:用于设置调试信息(React Developer Tools信息)
  • Setting method:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-YPJQPa0Y-1673683573537) (images/High-end Component-displayName.png)]

Pass props

  • Problem: If props are not passed, props will be lost.
  • Solution: WrappedComponentWhen rendering, pass state and props together to the component

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-RfqkEwsX-1673683573537) (images/transfer props.png)]

summary

  • Component communication is an essential part of building React applications
  • The flexibility of props makes components more powerful
  • State promotion is a common pattern for React components
  • Component life cycle helps to understand the running process of components
  • Hook functions allow developers to perform certain functions at specific times
  • render propsBoth patterns and higher-order components can realize the reuse of component state logic.
  • Component minimalist model:(state,props) => UI

React principles

Target

  • Be able to know that setState()updating data is asynchronous
  • Be able to know the conversion process of JSX syntax

setState()Description (★★★)

update data

  • setState()Updating data is asynchronous
  • Note: When using this syntax, setStatedo not rely on the previous setStatevalue.
  • Called multiple times setState, render will only be triggered once

Recommended syntax

  • Recommendation: Use setState((state,props) => {})syntax
  • Parameter state: represents the latest state
  • Parameter props: represents the latest props

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-DFZ0edW4-1673683573538) (images/recommended syntax.png)]

second parameter

  • Scenario: Perform an action immediately after status update (page completes re-rendering)
  • grammar:setState(update[,callback])

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-s4E3wOir-1673683573538) (images/second parameter.png)]

JSX syntax conversion process (★★★)

  • JSX is just createElement()syntactic sugar (simplified syntax) for methods
  • JSX syntax is compiled into createElement()methods by @babel/preset-react plugin
  • React element: is an object that describes what you want to see on the screen

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-lETXUoaE-1673683573538) (images/syntactic sugar.png)]

Guess you like

Origin blog.csdn.net/weixin_44694682/article/details/128686170