useState的回调版本,在第二个参数回调函数的参数中可以获取到更新后的state,进而在函数体中做一些逻辑操作。
// useState的回调版,
// 可以在第二个参数=>回调函数的第一个参数nextValue中拿到更新的state值,并在函数体中执行某些逻辑操作
// setState(
// (preValue) => preValue + value,
// (newValue) => {
// 逻辑操作
// }
// )
import { useEffect, useRef, useState } from 'react'
const useCallBackState = (initState) => {
const [state, setState] = useState(initState)
const isUpdate = useRef()
const setCallBackState = (state, cb) => {
setState((preValue) => {
isUpdate.current = cb
return typeof state === 'function' ? state(preValue) : state
})
}
useEffect(() => {
if (isUpdate.current) {
// 不设置回调函数的话 isUpdate.current 是undefined,所以不会执行
isUpdate.current(state)
}
}, [state])
return [state, setCallBackState]
}
export default useCallBackState