<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>
Reaktif tidak bergantung pada perpustakaan. Ini tentang memahami cara data mengalir dan berubah. Pelaksanaan ini membuktikan bahawa pengurusan negeri yang berkuasa adalah asli kepada JavaScript.
Atas ialah kandungan terperinci Pengurusan Negeri Reaktif Tanpa Perpustakaan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!