ข้ามไปยังเนื้อหา

Stores

นักพัฒนา React มักใช้ Context + useReducer, Redux หรือ Zustand เพื่อจัดการ shared state ข้ามคอมโพเนนต์ Svelte มี stores ในตัว: writable (อ่านและเขียนได้), readable (อ่านได้อย่างเดียว), และ derived (คำนวณค่าจาก stores อื่น) ใน markup ให้ใส่เครื่องหมาย $ นำหน้าชื่อ store เพื่อ auto-subscribe — Svelte จะ subscribe และ unsubscribe ให้อัตโนมัติ

React
// store.js (Zustand)
import { create } from 'zustand';
export const useCountStore = create(set => ({
count: 0,
increment: () => set(s => ({ count: s.count + 1 })),
reset: () => set({ count: 0 }),
}));
// Component.jsx
function Counter() {
const { count, increment } = useCountStore();
return <button onClick={increment}>Count: {count}</button>;
}
Svelte
<!-- store.js -->
import { writable } from 'svelte/store';
export const count = writable(0);
<!-- Counter.svelte -->
<script>
import { count } from './store.js';
</script>
<button onclick={() => count.update(n => n + 1)}>
Count: {$count}
</button>
React
// Zustand selector
const double = useCountStore(s => s.count * 2);
Svelte
<script>
import { derived } from 'svelte/store';
import { count } from './store.js';
const doubleCount = derived(count, $count => $count * 2);
</script>
<p>Double: {$doubleCount}</p>
คุณอ่านค่า writable store ชื่อ `count` ใน Svelte markup อย่างไร?
ความแตกต่างระหว่าง writable กับ readable store คืออะไร?
คุณสร้าง derived store ที่คำนวณ count * 2 จาก store `count` อย่างไร?