在组件外使用 Store

Pinia-React 的 Store 不仅可以在 React 组件内部使用,也可以在外部使用。对于 auth Store,自动生成的 useAuthStore() 是专门为组件设计的 Hook,而其他场景可以使用自动生成的 getAuthStore() 函数。原有的 useStore()getStore() 方法仍然保留。

getAuthStore 函数

当你通过 defineStore('auth', ...) 定义一个 Store 时,它会根据 Store ID 自动生成 useAuthStore(Hook)和 getAuthStore(普通函数)。

推荐的模式是从 Store 定义文件中同时导出这两个自动生成的函数。原有的 useStoregetStore 方法也仍然可以使用。

src/stores/auth-store.ts
import { defineStore } from 'pinia-react'

const { useAuthStore, getAuthStore } = defineStore('auth', {
  state: () => ({
    isAuthenticated: false,
    // ...
  }),
  actions: {
    logout() {
      this.isAuthenticated = false
    }
  }
})

使用示例

现在,你可以在任何 JavaScript 模块中导入 getAuthStore,比如在服务文件、API 客户端或另一个 Store 的 Action 中。

下面是一个在工具函数中调用 Store Action 的例子:

src/auth-service.ts
import { getAuthStore } from './stores/auth-store'

export function performLogout() {
  // 通过调用 getAuthStore() 获取 Store 实例
  const authStore = getAuthStore()

  // 现在你可以访问 state、getter 或 action 了
  if (authStore.isAuthenticated) {
    authStore.logout()
    console.log('用户已登出。')
  }
}

这种模式确保了无论你是在组件内部还是外部,访问的始终是同一个全局单例的 Store 实例。