Maison >interface Web >js tutoriel >Gestion d'état réactif sans bibliothèques
<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 ne dépend pas des bibliothèques. Il s'agit de comprendre comment les données circulent et changent. Cette implémentation prouve qu'une gestion d'état puissante est native de JavaScript.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!