diff --git a/src/hooks/createGlobalStateHook.ts b/src/hooks/createGlobalStateHook.ts new file mode 100644 index 0000000..fa3d266 --- /dev/null +++ b/src/hooks/createGlobalStateHook.ts @@ -0,0 +1,45 @@ +import {EventBus} from 'vtils' +import {useEffect, useState} from '@tarojs/taro' + +let stateIndex: number = 0 + +const store = new Map() + +const bus = new EventBus<{ + setState: (index: number, value: any) => void, +}>() + +bus.on('setState', (index, value) => { + store.set(index, value) +}) + +export function createGlobalStateHook() { + const index = stateIndex++ + return function useGlobalState(initialValue?: V): [V, (value: V) => void] { + const [value, setValue] = useState( + () => { + if (initialValue != null && !store.has(index)) { + store.set(index, initialValue) + } + return store.get(index) + }, + ) + const [off] = useState( + () => bus.on( + 'setState', + (targetIndex, targetValue) => { + if (targetIndex === index) { + setValue(targetValue) + } + }, + ), + ) + useEffect(() => off, [off]) + return [ + value, + function setValue(value: V) { + bus.emit('setState', index, value) + }, + ] + } +} diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 486069d..73019a9 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,4 +1,5 @@ // @index('./*', (pp, cc) => `export * from '${pp.path}'`) +export * from './createGlobalStateHook' export * from './useCustomNavBarFullHeight' export * from './useDidEnter' export * from './useDidLeave' diff --git a/src/hooks/useCustomNavBarFullHeight.ts b/src/hooks/useCustomNavBarFullHeight.ts index b90d2e1..2169f7c 100644 --- a/src/hooks/useCustomNavBarFullHeight.ts +++ b/src/hooks/useCustomNavBarFullHeight.ts @@ -1,32 +1,16 @@ -import {EventBus} from 'vtils' -import {useDispose} from './useDispose' -import {useState} from '@tarojs/taro' +import {createGlobalStateHook} from './createGlobalStateHook' -let customNavigationBarFullHeight = 0 - -const bus = new EventBus<{ - setCustomNavigationBarFullHeight: (height: number) => void, -}>() - -bus.on('setCustomNavigationBarFullHeight', height => { - customNavigationBarFullHeight = height -}) +const useGlobalHeight = createGlobalStateHook() export function useCustomNavigationBarFullHeight() { - const [height, setHeight] = useState(customNavigationBarFullHeight) - useDispose( - bus.on( - 'setCustomNavigationBarFullHeight', - height => setHeight(height), - ), - ) + const [height, setHeight] = useGlobalHeight(0) return { customNavigationBarFullHeight: height, setCustomNavigationBarFullHeight(height: number) { - bus.emit('setCustomNavigationBarFullHeight', height) + setHeight(height) }, resetCustomNavigationBarFullHeight() { - bus.emit('setCustomNavigationBarFullHeight', 0) + setHeight(0) }, } }