Ragdoll 專案的 createStore 狀態管理完整指南。當用戶詢問關於 Ragdoll 中的 createStore、Zustand、store 實作、狀態管理、Promise state、TrackedPromise、subscriptions、actions、跨 store 通信、useInjectedStores、並發控制策略、onMount、useProps 傳遞 props、runningActions loading 狀態等任何相關主題時觸發。也適用於「如何建立 store」、「store 之間如何通信」、「如何處理異步操作」、「Promise 狀態追蹤」、「跨 store 訂閱」、「action 互相呼叫」等問題。即使用戶只是提到 store、狀態、Zustand,也應該考慮使用此技能來提供準確且完整的資訊。
Ragdoll 使用基於 Zustand 的自訂 createStore 進行狀態管理(位於 next/lib/utils/stores/)。
回答原則: 繁體中文回覆,提供準確、完整的資訊,並輔以程式碼範例說明。
import { createStore } from '@/lib/utils/stores';
const useCounterStore = createStore({
name: 'counter',
states: {
count: { type: 'value', initialValue: 0 },
},
actions: {
increment: ({ state, setState }) => {
setState({ count: state.count + 1 });
},
},
});
function Counter() {
const { state, actions } = useCounterStore();
return <button onClick={() => actions.increment()}>{state.count}</button>;
}
// Value State
{ type: 'value', initialValue: T }
// Promise State(自動追蹤 status / value / error)
{ type: 'promise', initialValue: Promise<T> }
Promise State 與 TrackedPromise 詳見 references/tracked-promise.md