<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>
響應式並非依賴函式庫。它關乎理解數據如何流動和變化。此實作證明了強大的狀態管理是JavaScript的原生特性。
以上是無需庫的反應式狀態管理的詳細內容。更多資訊請關注PHP中文網其他相關文章!