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(_ => _?.()); 12*4060c00aS猫头猫 }; 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; 26*4060c00aS猫头猫 }; 27233cafa6S猫头猫} 28