Home >Web Front-end >JS Tutorial >Reactive State Management Without Libraries
<code class="language-javascript">export class State<IState extends Record<string, unknown>> { private data = new Map<keyof IState, IState[keyof IState]>(); private subscribers = new Map<string, ((...args: any[]) => void)[]>(); set(name: keyof IState, value: IState[keyof IState]): void { this.data.set(name, value); this.publish(`change:${String(name)}`, value); } get(name: keyof IState): IState[keyof IState] | undefined { return this.data.get(name); } has(name: keyof IState): boolean { return this.data.has(name); } clear(): void { this.data.clear(); this.publish('clear'); } publish(name: string, ...args: any[]): void { this.subscribers.get(name)?.forEach(fn => fn(...args)); } subscribe(name: string, fn: (...args: any[]) => void): void { this.subscribers.has(name) ? this.subscribers.get(name)!.push(fn) : this.subscribers.set(name, [fn]); } unsubscribe(name: string, fn: (...args: any[]) => void): void { if (this.subscribers.has(name)) { const idx = this.subscribers.get(name)!.indexOf(fn); if (idx > -1) this.subscribers.get(name)!.splice(idx, 1); } } unsubscribeAll(name: string): void { this.subscribers.delete(name); } }</code>
<code class="language-javascript">function UserProfile() { const state = new State(); const [userData, setUserData] = useState({ name: state.get('name') || '', age: state.get('age') || 0 }); // 通过状态变化实现自动响应 state.subscribe('change:name', (newName) => { setUserData(prev => ({ ...prev, name: newName })); }); return ( <div> <input type="text" onChange={e => state.set('name', e.target.value)} /> </div> ); }</code>
Reactive is not dependent on libraries. It's about understanding how data flows and changes. This implementation proves that powerful state management is native to JavaScript.
The above is the detailed content of Reactive State Management Without Libraries. For more information, please follow other related articles on the PHP Chinese website!