useState

useState 可组合函数创建响应式且支持服务器端渲染 (SSR) 的共享状态。

用法

¥Usage

// Create a reactive state and set default value
const count = useState('counter', () => Math.round(Math.random() * 100))
Read more in Docs > Getting Started > State Management.
由于 useState 中的数据将被序列化为 JSON,因此务必确保它不包含任何无法序列化的内容,例如类、函数或符号。
useState 是一个由编译器转换的保留函数名,因此你不应将自己的函数命名为 useState。¥useState is a reserved function name transformed by the compiler, so you should not name your own function useState.

使用 shallowRef

¥Using shallowRef

如果你不需要状态高度响应,可以将 useStateshallowRef 结合使用。当你的状态包含大型对象和数组时,这可以提高性能。

¥If you don't need your state to be deeply reactive, you can combine useState with shallowRef. This can improve performance when your state contains large objects and arrays.

const state = useState('my-shallow-state', () => shallowRef({ deep: 'not reactive' }))
// isShallow(state) === true

类型

¥Type

useState<T>(init?: () => T | Ref<T>): Ref<T>
useState<T>(key: string, init?: () => T | Ref<T>): Ref<T>
  • key:一个唯一键,用于确保数据提取在请求之间正确地去重。如果你未提供密钥,那么系统将为你生成一个与 useState 实例的文件和行号唯一的密钥。
  • init:一个函数,用于在未初始化时提供状态的初始值。此函数还可以返回 Ref
  • T:(仅限 TypeScript)指定状态类型