React 中的常见 API 和生命周期函数

目录

useState

useState 是 React 的一个 Hook,用于在函数组件中添加状态。通过 useState,我们可以在函数组件中创建和管理状态变量,每当状态变量更新时,组件将重新渲染以显示最新的状态。

useEffect

useEffect 是 React 的另一个 Hook,用于处理副作用。副作用是指在组件渲染过程中可能产生的任何操作,例如访问 DOM、发起网络请求、订阅事件等。通过 useEffect,我们可以在组件渲染后执行这些操作。

useRef

useRef 用于在函数组件中创建可变的引用。它提供了一个持久的引用,使我们可以在多次渲染之间存储和访问数据。在上面的例子中,我们使用 useRef 创建了 divRef、inputRef 和 buttonRef,分别引用了 div、input 和 button 元素。

代码示例

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 是 React 中的一个属性,用于将 HTML 字符串插入到组件中。它提供了一种绕过 React 的默认转义机制的方法,但也带来了潜在的安全风险,因此应该谨慎使用。

生命周期函数

constructor

这是组件的构造函数,在组件创建时被调用。在 constructor 中,我们通常进行一些初始化操作,如设置初始状态,绑定事件处理函数等。在构造函数中,可以通过 this.state 初始化组件的状态。

componentDidMount

这是组件的生命周期函数,在组件渲染完成后被调用。在 componentDidMount 中,我们通常进行一些异步操作,如数据请求、订阅事件等。在该函数中,可以修改组件的状态,这将导致组件重新渲染。

static getDerivedStateFromProps

这是一个静态函数,用于根据传入的 props 和当前的 state 计算并返回一个新的 state。getDerivedStateFromProps 在组件创建和更新时都会被调用,用于根据传入的 props 更新组件的状态。

shouldComponentUpdate

这是一个生命周期函数,用于判断组件是否需要重新渲染。在 shouldComponentUpdate 中,我们可以根据传入的 nextProps 和 nextState 来决定是否重新渲染组件。如果返回 true,则组件将重新渲染;如果返回 false,则组件不会重新渲染。

componentDidUpdate

这是组件的生命周期函数,在组件更新后被调用。在 componentDidUpdate 中,我们通常进行一些副作用操作,如更新 DOM、请求数据等。在该函数中,可以根据 prevProps 和 prevState 来进行一些条件判断,执行相应的操作。

componentWillUnmount

这是组件的生命周期函数,在组件即将卸载时被调用。在 componentWillUnmount 中,我们通常进行一些清理操作,如取消订阅、清除定时器等。在该函数中,应该避免执行 setState 操作,因为组件即将卸载,不再需要更新状态。

以上是 React 中常见的一些 API 和生命周期函数的介绍。通过合理地使用这些 API 和生命周期函数,我们可以更加灵活和高效地构建 React 应用。但需要注意的是,随着 React 的不断发展,一些生命周期函数可能会被废弃或替代,请根据具体的 React 版本和需求做出相应的选择。希望本篇博客对你在学习和使用 React 中有所帮助!

代码示例:

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></>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_60895836/article/details/131940984