Skip to content

Commit

Permalink
feat(hooks): 新增 createGlobalStateHook
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Aug 27, 2019
1 parent eae65c8 commit 173ddb0
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 21 deletions.
45 changes: 45 additions & 0 deletions src/hooks/createGlobalStateHook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {EventBus} from 'vtils'
import {useEffect, useState} from '@tarojs/taro'

let stateIndex: number = 0

const store = new Map<number, any>()

const bus = new EventBus<{
setState: (index: number, value: any) => void,
}>()

bus.on('setState', (index, value) => {
store.set(index, value)
})

export function createGlobalStateHook<V>() {
const index = stateIndex++
return function useGlobalState(initialValue?: V): [V, (value: V) => void] {
const [value, setValue] = useState<V>(
() => {
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)
},
]
}
}
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @index('./*', (pp, cc) => `export * from '${pp.path}'`)
export * from './createGlobalStateHook'
export * from './useCustomNavBarFullHeight'
export * from './useDidEnter'
export * from './useDidLeave'
Expand Down
26 changes: 5 additions & 21 deletions src/hooks/useCustomNavBarFullHeight.ts
Original file line number Diff line number Diff line change
@@ -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<number>()

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)
},
}
}

0 comments on commit 173ddb0

Please sign in to comment.