1*233cafa6S猫头猫import {useEffect, useState} from 'react'; 2*233cafa6S猫头猫 3*233cafa6S猫头猫export default class StateMapper<T> { 4*233cafa6S猫头猫 private getFun: () => T; 5*233cafa6S猫头猫 private cbs: Set<Function> = new Set([]); 6*233cafa6S猫头猫 constructor(getFun: () => T) { 7*233cafa6S猫头猫 this.getFun = getFun; 8*233cafa6S猫头猫 } 9*233cafa6S猫头猫 10*233cafa6S猫头猫 notify = () => { 11*233cafa6S猫头猫 this.cbs.forEach(_ => _?.()); 12*233cafa6S猫头猫 } 13*233cafa6S猫头猫 14*233cafa6S猫头猫 useMappedState = () => { 15*233cafa6S猫头猫 const [_state, _setState] = useState<T>(this.getFun); 16*233cafa6S猫头猫 const updateState = () => { 17*233cafa6S猫头猫 _setState(this.getFun()); 18*233cafa6S猫头猫 }; 19*233cafa6S猫头猫 useEffect(() => { 20*233cafa6S猫头猫 this.cbs.add(updateState); 21*233cafa6S猫头猫 return () => { 22*233cafa6S猫头猫 this.cbs.delete(updateState); 23*233cafa6S猫头猫 }; 24*233cafa6S猫头猫 }, []); 25*233cafa6S猫头猫 return _state; 26*233cafa6S猫头猫 } 27*233cafa6S猫头猫} 28