其他分享
首页 > 其他分享> > 自定义hooks实现在useState改变值之后立刻获取到最新的值

自定义hooks实现在useState改变值之后立刻获取到最新的值

作者:互联网

自定义hooks实现在useState改变值之后立刻获取到最新的值

import React from 'react'
function App () {
 let [count, setCount] = React.useState(0)

 const add = () => {
   setCount(count + 1)
   console.log(count)
}

 return (

   <div>
     <h1>{count}</h1>
     <button onClick={add}>点我加 1 </button>
   </div>

)
}
export default App;

以上代码每次点击按钮得到的 count 值都是上一次的值

再来看看以下代码

import React from 'react'
import useSyncCallback from './hooks/hook'
function App () {
 let [count, setCount] = React.useState(0)
 
 const add = () => {
   setCount(count + 1)
   fnc()
}
 const fnc = useSyncCallback(() => {
   console.log(count)
})

 return (
   <div>
     <h1>{count}</h1>
     <button onClick={add}>点我加 1 </button>
   </div>
)
}
export default App;

以上代码可以得到更新之后的值

下面写上 useSyncCallback 函数的实现

import { useEffect, useState, useCallback } from "react";

const 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;
};

export default useSyncCallback;

 

标签:count,const,自定义,hooks,useSyncCallback,proxyState,current,useState
来源: https://www.cnblogs.com/liujis/p/16053144.html