|
@@ -1,9 +1,10 @@
|
|
|
import React, { useState, createContext, useContext, PropsWithChildren } from 'react'
|
|
|
|
|
|
// 构造器函数,用于创建全局状态管理钩子
|
|
|
-function createGlobalStateHook<T>(initialState?: T) {
|
|
|
+function createGlobalStateHook<T,G=undefined>(initialState?: T, getterSetter?: (state?: T)=>G) {
|
|
|
const GlobalStateContext = createContext<T|undefined>(initialState)
|
|
|
const GlobalStateUpdateContext = createContext<React.Dispatch<React.SetStateAction<T|undefined>>>(() => {})
|
|
|
+ const GlobalStateGetterContext = createContext<G|undefined>(undefined)
|
|
|
|
|
|
|
|
|
function useGlobalState() {
|
|
@@ -14,13 +15,20 @@ function createGlobalStateHook<T>(initialState?: T) {
|
|
|
return useContext(GlobalStateUpdateContext)
|
|
|
}
|
|
|
|
|
|
+ function useGlobalStateGetter() {
|
|
|
+ return useContext(GlobalStateGetterContext)
|
|
|
+ }
|
|
|
+
|
|
|
function GlobalStateProvider({ children }: PropsWithChildren) {
|
|
|
const [globalState, setGlobalState] = useState(initialState)
|
|
|
+ const getters = getterSetter?.(globalState)
|
|
|
|
|
|
return (
|
|
|
<GlobalStateContext.Provider value={globalState}>
|
|
|
<GlobalStateUpdateContext.Provider value={setGlobalState}>
|
|
|
- {children}
|
|
|
+ <GlobalStateGetterContext.Provider value={getters}>
|
|
|
+ {children}
|
|
|
+ </GlobalStateGetterContext.Provider>
|
|
|
</GlobalStateUpdateContext.Provider>
|
|
|
</GlobalStateContext.Provider>
|
|
|
)
|
|
@@ -30,6 +38,7 @@ function createGlobalStateHook<T>(initialState?: T) {
|
|
|
useGlobalState,
|
|
|
useGlobalStateUpdate,
|
|
|
GlobalStateProvider,
|
|
|
+ useGlobalStateGetter
|
|
|
}
|
|
|
}
|
|
|
|