🦄 refactor(ID1000779): 八、收藏功能;
【八、收藏功能;】 https://www.tapd.cn/53459131/prong/stories/view/1153459131001000779
This commit is contained in:
+29
-1
@@ -1,6 +1,7 @@
|
||||
import Taro from '@tarojs/taro'
|
||||
import dayjs from 'dayjs'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { SetStateAction } from 'react'
|
||||
import { SubscriptionMessageApi } from '@/api/user'
|
||||
|
||||
// 倒计时hook
|
||||
@@ -91,3 +92,30 @@ export const UseSubscriptionMessage = () => {
|
||||
openSubscriptionMessage,
|
||||
}
|
||||
}
|
||||
|
||||
interface UsePropsValueOptions<T> {
|
||||
value?: T
|
||||
defaultValue: T
|
||||
onChange?: (v: T) => void
|
||||
}
|
||||
|
||||
export function usePropsValue<T>(options: UsePropsValueOptions<T>) {
|
||||
const { value, defaultValue, onChange } = options
|
||||
|
||||
const [, setForceUpdate] = useState({})
|
||||
|
||||
const stateRef = useRef<T>(value !== undefined ? value : defaultValue)
|
||||
if (value !== undefined) {
|
||||
stateRef.current = value
|
||||
}
|
||||
|
||||
const setState = useCallback((v: SetStateAction<T>, forceTrigger = false) => {
|
||||
// `forceTrigger` 意思是 触发 `onChange` 不管 `v` 是否和 `stateRef.current` 相等
|
||||
const nextValue = typeof v === 'function' ? (v as (prevState: T) => T)(stateRef.current) : v
|
||||
if (!forceTrigger && nextValue === stateRef.current) { return }
|
||||
stateRef.current = nextValue
|
||||
setForceUpdate({})
|
||||
return onChange?.(nextValue)
|
||||
}, [])
|
||||
return [stateRef.current, setState] as const
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user