1233cafa6S猫头猫import {useEffect, useState} from 'react'; 2233cafa6S猫头猫 3233cafa6S猫头猫export default class StateMapper<T> { 4233cafa6S猫头猫 private getFun: () => T; 5233cafa6S猫头猫 private cbs: Set<Function> = new Set([]); 6233cafa6S猫头猫 constructor(getFun: () => T) { 7233cafa6S猫头猫 this.getFun = getFun; 8233cafa6S猫头猫 } 9233cafa6S猫头猫 10233cafa6S猫头猫 notify = () => { 11233cafa6S猫头猫 this.cbs.forEach(_ => _?.()); 124060c00aS猫头猫 }; 13233cafa6S猫头猫 14233cafa6S猫头猫 useMappedState = () => { 15233cafa6S猫头猫 const [_state, _setState] = useState<T>(this.getFun); 16233cafa6S猫头猫 const updateState = () => { 17233cafa6S猫头猫 _setState(this.getFun()); 18233cafa6S猫头猫 }; 19233cafa6S猫头猫 useEffect(() => { 20233cafa6S猫头猫 this.cbs.add(updateState); 21233cafa6S猫头猫 return () => { 22233cafa6S猫头猫 this.cbs.delete(updateState); 23233cafa6S猫头猫 }; 24233cafa6S猫头猫 }, []); 25233cafa6S猫头猫 return _state; 264060c00aS猫头猫 }; 27233cafa6S猫头猫} 28*50800d1bS猫头猫 29*50800d1bS猫头猫export class GlobalState<T> { 30*50800d1bS猫头猫 private value: T; 31*50800d1bS猫头猫 private stateMapper: StateMapper<T>; 32*50800d1bS猫头猫 33*50800d1bS猫头猫 constructor(initValue: T) { 34*50800d1bS猫头猫 this.value = initValue; 35*50800d1bS猫头猫 this.stateMapper = new StateMapper(this.getValue); 36*50800d1bS猫头猫 } 37*50800d1bS猫头猫 38*50800d1bS猫头猫 public getValue = () => { 39*50800d1bS猫头猫 return this.value; 40*50800d1bS猫头猫 }; 41*50800d1bS猫头猫 42*50800d1bS猫头猫 useValue() { 43*50800d1bS猫头猫 return this.stateMapper.useMappedState(); 44*50800d1bS猫头猫 } 45*50800d1bS猫头猫 46*50800d1bS猫头猫 setValue(value: T) { 47*50800d1bS猫头猫 this.value = value; 48*50800d1bS猫头猫 this.stateMapper.notify(); 49*50800d1bS猫头猫 } 50*50800d1bS猫头猫} 51