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
本文介绍了如何在React中创建一个定制的useCallBackState Hook,该Hook允许在更新状态时提供一个回调函数,以便在状态改变后立即进行逻辑操作。通过在useState中封装一个回调版本,开发者可以在状态更新后立即获取并利用新的状态值执行特定任务。
5065

被折叠的 条评论
为什么被折叠?



