Common APIs and lifecycle functions in React

Table of contents

useState

useState is a Hook of React for adding state in function components. With useState, we can create and manage state variables in function components, and whenever the state variables are updated, the component will re-render to display the latest state.

useEffect

useEffect is another Hook in React for handling side effects. Side effects refer to any operations that may occur during component rendering, such as accessing the DOM, initiating network requests, subscribing to events, and so on. With useEffect we can perform these operations after the component renders.

useRef

useRef is used to create mutable references in function components. It provides a persistent reference that allows us to store and access data between renders. In the above example, we used useRef to create divRef, inputRef and buttonRef, referencing the div, input and button elements respectively.

code example

import {Ref, useEffect, useRef} from "react";
// @ts-ignore
import React from "react";

const Demo=React.forwardRef((props:any,ref:Ref<HTMLInputElement>)=>{
 return (
     <>
        <input type="text" ref={ref}/>
     </>
 )
})
function Contact() {
    const divRef=useRef<HTMLDivElement>(null);
    const inputRef=useRef<HTMLInputElement>(null);
    const buttonRef=useRef<HTMLButtonElement>(null);
    useEffect(()=>{
        console.log(inputRef.current)
      if(inputRef.current) {
          inputRef.current.focus()
      }
        console.log(buttonRef.current)
    })
    function changeContent(){
        if(divRef.current){
            divRef.current.innerHTML="<h1>hello</h1>"
        }
    }
  return (
    <div>
      <h1>Contact</h1>
        <br/>
        <Demo ref={inputRef}/>
        <button onClick={()=>{
            if(inputRef.current){
                inputRef.current.focus()
            }
        }}>focus</button>
        <div ref={divRef} onClick={changeContent}>click</div>
        <div dangerouslySetInnerHTML={
   
   {__html:"<h1>hekko</h1>"}}></div>
        <input type="text" ref={inputRef}/>
        <button ref={buttonRef}>button</button>
    </div>
  );
}
export default Contact;

dangerouslySetInnerHTML

dangerouslySetInnerHTML is a property in React that is used to insert HTML strings into components. It provides a way to bypass React's default escaping mechanism, but also poses a potential security risk and should be used with caution.

生命周期函数

constructor

This is the component's constructor, which is called when the component is created. In the constructor, we usually perform some initialization operations, such as setting the initial state, binding event handlers, and so on. In the constructor, the state of the component can be initialized through this.state.

componentDidMount

This is the lifecycle function of the component, which is called after the component is rendered. In componentDidMount, we usually perform some asynchronous operations, such as data requests, subscription events, and so on. In this function, the state of the component can be modified, which will cause the component to re-render.

static getDerivedStateFromProps

This is a static function that calculates and returns a new state based on the passed in props and the current state. getDerivedStateFromProps is called when the component is created and updated, and is used to update the state of the component according to the passed in props.

shouldComponentUpdate

This is a lifecycle function used to determine whether the component needs to be re-rendered. In shouldComponentUpdate, we can decide whether to re-render the component according to the incoming nextProps and nextState. If it returns true, the component will re-render; if it returns false, the component will not re-render.

componentDidUpdate

This is the lifecycle function of the component, which is called after the component is updated. In componentDidUpdate, we usually perform some side effects, such as updating DOM, requesting data, and so on. In this function, some conditions can be judged according to prevProps and prevState, and corresponding operations can be performed.

componentWillUnmount

This is the lifecycle function of the component, which is called when the component is about to be unmounted. In componentWillUnmount, we usually perform some cleanup operations, such as unsubscribing, clearing timers, etc. In this function, the setState operation should be avoided, because the component is about to unmount and no longer needs to update the state.

The above is an introduction to some common APIs and life cycle functions in React. By using these APIs and life cycle functions reasonably, we can build React applications more flexibly and efficiently. However, it should be noted that with the continuous development of React, some life cycle functions may be abandoned or replaced, please make corresponding choices according to the specific React version and requirements. Hope this blog helps you in learning and using React!

Code example:

import {Component} from "react";
import {Button} from "antd";

interface IState{
    counter:number
}
export default class Index extends Component <any,any>{
    constructor(props: any, context: any) {
        super(props, context);
        this.state={
            counter:0
        }
        console.log("constructor")
    }
    componentDidMount() {
        console.log("componentDidMount")
    }
    static getDerivedStateFromProps(props: any, state: any) {
        console.log("getDerivedStateFromProps")
        return null
    }
    shouldComponentUpdate(nextProps: Readonly<any>, nextState: Readonly<any>, nextContext: any): boolean {
        console.log("shouldComponentUpdate")
        return nextState.counter!<=5
    }

    add=()=>{
        this.setState({
            counter:this.state.counter+1
        })
    }
    componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<any>, snapshot?: any) {
        console.log("componentDidUpdate")
    }

    componentWillUnmount() {
        console.log("componentWillUnmount")
    }

    render(){
        console.log("render")
        return(
            <>
                <div>{this.state.counter}</div>
                <Button onClick={this.add}>add</Button></>
        )
    }
}

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/131940984