快速开始

环境要求

  • ES6+
  • React 18+

安装

使用你喜欢的包管理器安装 pinia-react:

npm
yarn
pnpm
bun
npm install pinia-react

初始化

以下示例适用于已有 React 项目的浏览器客户端入口,假设 HTML 中已有 id="app" 的挂载元素。在渲染应用前调用一次 createPinia(),初始化供 Store 使用的状态容器。Next.js App Router 请使用 Next.js 集成指南中的根级 Provider 方案。

TSX
JSX
src/index.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { App } from './App'
import { createPinia } from 'pinia-react'

createPinia()

const container = document.querySelector('#app')
if (!container) throw new Error('Missing #app root element')

createRoot(container).render(
  <StrictMode>
    <App />
  </StrictMode>
)

定义 Store

Store 将共享状态(State)、衍生数据(Getter)和修改状态的方法(Action)放在一起。在 src/stores/counter.ts 中定义一个计数器:

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

export const { useCounterStore, getCounterStore } = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  getters: {
    double: state => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

defineStore('counter', ...) 会生成 useCounterStore 和 getCounterStore。组件中使用 Hook;组件外使用普通函数 getCounterStore(),详见在组件外使用 Store。

在组件中使用

在 src/App.tsx 中读取 count,并通过 Action 修改它:

src/App.tsx
import { useCounterStore } from './stores/counter'

export function App() {
  const counter = useCounterStore()

  return (
    <div>
      <p>当前计数: {counter.count};两倍: {counter.double}</p>
      <button onClick={() => counter.increment()}>增加</button>
    </div>
  )
}

启动现有项目的开发服务器,点击“增加”,计数应从 0 变为 1。Store 的公开状态只读,不要在组件中直接执行 counter.count++。

JSX 项目可使用相同的 Store 和组件代码,分别保存为 .js 和 .jsx 文件。

继续阅读 State、Getter 和 Action,了解类型推导、衍生数据和异步修改。

独立挂载树、请求与最终卸载请参阅实例归属与销毁。disposePinia 是显式且不可逆的所有者操作,不是 Effect cleanup;Provider 卸载不会自动销毁。