react hooks小记

90 阅读2分钟

hooks

通过 Hooks 可以创建出带有状态的函数组件

Hooks规则: (1)只能在 React 函数组件中使用; (2)只能在 React 函数组件最顶层使用 Hook,不要在循环,条件或嵌套函数中调用 Hook;

useState

组件自身的数据被称作 state。使用 useState 可以创建 state。

const [stateValue, setStateValue] = useState(initialValue);

调用它时需要传递一个初始值;它会返回一个数组,数组中包含两个元素,第一个是当前状态,第二个是更新状态的函数。

useEffect

执行副作用操作,如发起数据请求,事件处理,清除effect。

useEffect(()=>{},[])

useEffect 需要两个参数,第一个是副作用函数,第二个是依赖项数组。每当依赖项数组发生变化时,副作用函数会重新执行.

useRef

通过 ref.current 访问到元素.

const refContainer = useRef(initialValue);
import React, { useEffect, useRef } from "react";
function App() {
    const h1Ref=useRef(null)
    useEffect(()=>{
        console.log('1111',h1Ref.current);
    })
    return (
      <div className="App">
        <h1 ref={ h1Ref }>this is h1</h1>    
      </div>
    );
}
export default App;

useContext

跨组件传参,调用 useContext 函数,将 Context 对象作为参数传递进去。

const value = useContext(MyContext);
import React, {useContext,createContext, useState } from "react";
// hook-useContext-跨组件传递参数
const Context=createContext()
function ComA(){
    const count=useContext(Context)
    return (
       <>
        <div>this is A:{count}</div>
        <ComC></ComC>
        </>
    )
}
function ComC(){
    const count=useContext(Context)
    return (
        <div>this is C:{count}</div>
    )
}
function App() {
   const [count,setCount]=useState(18)
    return (
        <Context.Provider value={count}>
            <div className="App">
                <ComA></ComA>
                <button onClick={()=>setCount(count+1)}>click</button>
            </div>
      </Context.Provider>
    );
}
export default App;


useReducer

useReducer 是用来替代 useState 的 Hook,它用来处理复杂的状态逻辑。

const [state, dispatch] = useReducer(reducer, initialArg, init);
import React, {useState,useReducer} from "react";
import { Button } from 'antd';
// useReducer 整合器
function reducer(state,action){
    console.log('reducer执行',state,action);
    switch(action.type){
        case 'add':
            return state+1
        case 'des':
            return state-1
        default:
            throw new Error();
    }
   
}
function ReducerDemo(){
    // 1、使用useState
    // const [count,setCount]=useState(0)
    // const incresement=()=>{
    //     setCount(count+1)
    // }
    // const decresement=()=>{
    //     setCount(count-1)
    // }
    //2、使用reducer
    const [count,countDispatch]=useReducer(reducer,1)

    return(
        <div>
            <p>{count}</p>
            <Button onClick={()=>countDispatch({type:'add'})} type="primary">incresement</Button>
            <Button onClick={()=>countDispatch({type:'des'})} >decresement</Button>
        </div>
    )
}

ReactDOM.render(<ReducerDemo />, document.getElementById('app'));

useCallback

用于缓存函数,参数:回调函数,依赖数组param; 只有当依赖项发生变化时,回调函数才会重新创建

useCallback(()=>{},[param])
import React from "react";

function Button ({ onClick }) {
    console.log("button render");
    return <button onClick={onClick}>count++</button>;
  };
  
  const MemoButton = React.memo(Button);
  function Counter() {
    const [count, setCount] = React.useState(0);
    const onClick = React.useCallback(() => {
      setCount((count) => count + 1);
    }, []);
  
    return (
      <>
        <p>count:{count}</p>
        <MemoButton onClick={onClick} />
      </>
    );
  }

ReactDOM.render(<Counter />, document.getElementById('app'));

useMemo

用于缓存函数的返回值,第一个参数为要缓存的函数(注意实际被缓存的是函数被执行过后的值),第二个参数为依赖项数组; 如果依赖发生了变化,那么就会重新执行这个函数,得到新的返回值;否则当组件重新渲染时,不会重新执行这个函数,而是直接取被缓存的该函数的返回值。

自定义hook

import { useEffect, useState } from "react";
//缓存数据
export function useLocalstore(key,defaultMessage){
    const [message,setMessage]=useState(defaultMessage)
    useEffect(()=>{
        window.localStorage.setItem(key,message)
    },[key,message])
    return [message,setMessage]
}
// 使用自定义hook函数
function App() {
    const [message,setMessage]=useLocalstore('name','dora')
    function handleClick(){
        setMessage('jack')
    }
    return (
      <div className="App">
           {message}
          <button onClick={handleClick}>click</button>
      </div>
    );
}
export default App;