react hook 获取setState的新值

  1. 利用useRef 存储最新值
 	let [count,setCount] = useState(0)
    let countRef = useRef(count)
    let handleClick = function (){
        setCount((prev)=>{
            countRef.current = prev+1
            return countRef.current
        })
            console.info(countRef.current)
    }
  1. 利用useRef
	let [count,setCount] = useState(0)
    let countRef = useRef(count)
    countRef.current = count
    let handleClick = function (){
        setCount((prev)=>{
            return prev+1
        })
        setTimeout(()=>{
            console.info(countRef.current)
        })
    }
  1. 封装一个自定义函数
//useSyncCallback.js
import {useEffect,useState,useCallback} from 'react'
export default function useSyncCallback(callback){
    const [proxyState, setProxyState] = useState({ current: false });
    const Func = useCallback(() => {
            setProxyState({ current: true });
          }, [proxyState])
    useEffect(() => {
        if (proxyState.current === true) setProxyState({ current: false });
        }, [proxyState]);
    useEffect(() => {
        proxyState.current && callback();
        });
    return Func
};

使用方法:

import React,{useState,useCallback,useRef} from 'react'
import {Button,Input} from 'antd'
import HighFrequency from '../../utils/HighFrequency';
import useSyncCallback from '../../utils/useSyncCallback'

export default function HookOptimization() {
	let [name,setName]=useState('_')
    let handleChange = HighFrequency.debounce(function(e){
        setName(()=>{
            return e.target.value
        })
        fnc()
    })
    const fnc = useSyncCallback(() => {
        console.log(name)
      })
  return (
    
) }

你可能感兴趣的:(react.js,javascript,前端)