React Hooks学习笔记

发布于:2024-07-11 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、usestate的使用方法-初始化state函数

import React, { useState } from "react";
function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>点击{count}次</p>
      <button onClick={() => setCount(count + 1)}>点击</button>
    </div>
  )

运行效果图:

二、useEffect的使用方法-执行钩子函数的操作

import React, { useState, useEffect } from "react";
const [count,setCount] = useState(0);

  const btnClick = () =>{
    setCount(count + 1);
  }

  useEffect(() =>{
    console.log("执行了useEffect");
    document.title = '点击了{count}次'
  })

  return(
    <div>
      <p>点击{count}次</p>
      <button onClick = {() => { btnClick()}}>点击</button>
    </div>
  )

运行效果图:

三、useContext的使用方法-实现组件之间的共享

import React, { useContext, createContext } from "react"; 
const myContext = createContext();

  function App(){
    const value = useContext(myContext);
    return(
      <div>{value}</div>
    );
  }

  export default function MyComponent(){
    return(
      <myContext.Provider value={100}>
      <div>hello world</div>
      <App/>
      </myContext.Provider>
    );
  }

运行效果图:

四、useReducer的使用方法-把组件的所有状态更新逻辑整合到reducer这个函数中

import React, { useReducer } from "react";
function Counter(){
    const initState = {count: 0 };
    function reducer(state, action){
      switch(action.type){
        case 'increment':
          return { count: state.count + 1};
          case 'decrement':
            return {count: state.count - 1};
            default:
              return{ count: state};
      }
    }
    const [state,dispatch] = useReducer(reducer, initState);
    return(
      <div>
        <button onClick={() => dispatch({ type:'decrement'})}>减</button>
        <span>{state.count}</span>
        <button onClick={() => dispatch({ type:'increment'})}>加</button>
      </div>
    )
  }

  export default Counter;

运行效果图:

五、useMemo的使用方法-对数据的记忆,具有缓存功能,类似于Vue的计算属性

useMemo 接收2个参数,第1个参数为执行运算的函数,第2个参数为要监控的状态。

import React, {  useMemo } from "react";
function Counter(){
    const [count, setCount] = useState(0);
    const value = useMemo(function(){
      return count * 2;
    },[count]);//数组中的元素就是useMemo监控的状态
  return (
    <div>
      <h3>{count}</h3>
      <h3>{value}</h3>
      <button onClick={() => setCount(count + 1)}>按钮</button>
    </div>
  )
  }

  export default Counter;

运行效果图:

六、useRef的使用方法-获取组件中的 dom 对象

import React, { useRef  } from "react"; 
function App(){
    const refObj = useRef();
    console.log(refObj);
    function getRef(){
     console.log(refObj);     
    }
    return(
      <div>
        <div ref={refObj}>hello</div>
        <button onClick={getRef}>按钮</button>
      </div>
    );
  }
export default App;

运行效果图:

七、useCallback的使用方法-允许多次渲染中缓存数据,返回一个memoized回调函数,对函数的记忆

有2个函数,第一个参数是要缓存的函数,第二个参数是一个数组 (响应值变化时更新函数)

import React, { useCallback, memo   } from "react";
 function App(){
    const[count, setCount] = useState(1);
    const fn = useCallback(function (){
      return count;
    },[count]);
    return(
      <div>
        {count}
        <button onClick={() => setCount(count + 1)}>增加</button>
        <Heads fn={fn}></Heads>
      </div>
    );
  }

  const Heads = memo(function(props){
    return <button onClick={() =>console.log(`我被渲染了${props.fn()}次`)}>按钮</button>
  });
export default App;

运行效果图:

八、useImperativeHandle和forwardRef的使用方法

  1. useImperativeHandle-自定义由 ref 暴露出来的程序、数据或地址表等的入口地址,可应用于父组件访问子组件的场景。
  2. forwardRef-允许组件使用 ref 将一个 DOM 节点暴露给父组件
import React, {useRef,useImperativeHandle, forwardRef   } from "react"; 
function App(){
    const CounterRef = useRef();
    function click(){
      const { count, setCount } = CounterRef.current || {};
      setCount(count + 1);
    }
    return(
      <>
      <Counter ref={CounterRef}></Counter>
      <button onClick={click}>按钮</button>
      </>
    );
  }

  const Counter = forwardRef((props,ref) =>{
    const [count, setCount] = useState(0);
    useImperativeHandle(ref,() => ({ count, setCount }), [count]);
    return<>
    {count}
    </>
  });

export default App;

运行效果图:


网站公告

今日签到

点亮在社区的每一天
去签到