ITADN
nanostores/preact
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

Nano Stores Preact

Nano Stores 的 Preact 集成,一个拥有众多原子化、可 Tree-shaking 存储的微型状态管理器。

  • 小巧。 小于 1 KB。零依赖。
  • 快速。 对于小型原子存储和派生存储,您无需在每次存储更改时为所有组件调用 选择器函数。
  • 可 Tree-shaking。 代码块仅包含该代码块中组件所使用的存储。
  • 旨在将逻辑从组件迁移到存储中。
  • 具有良好的 TypeScript 支持。
import { useStore } from '@nanostores/preact'

import { $profile } from '../stores/profile.js'

export const Header = () => {
  const profile = useStore($profile)
  return <header>{profile.name}</header>
}

Nano Stores Preact 由 Evil Martians 开发,这是一家专注于 开发者工具、AI 和网络安全初创企业 的美国设计与工程咨询公司。


选项

按键

使用 keys 选项,仅在特定按键变化时重新渲染:

export const Header = () => {
  const profile = useStore($profile, { keys: 'name' })
  return <header>{profile.name}</header>
}

监听基础键时,如果其任何嵌套属性发生变更,将自动触发重新渲染。

// Will listen for all changes in profile object
const profile = useStore($profile, { keys: ['profile'] })

SSR

在 VDom 中,SSR 可能非常复杂。为了避免 hydration 错误, 你需要在服务器端 HTML 渲染结束时和客户端首次 DOM 渲染期间 拥有完全相同的 stores 状态。

对于简单的解决方案,你可以通过 ssr: 'initial' 在服务器端禁用任何 store 更新:

export const Header = () => {
  const profile = useStore($profile, { ssr: 'initial' })

  // Server render and client hydration use store's initial value.
  // After hydration, client re-renders with the current value.
  return <header>{profile.name}</header>
}

对于在 SSR 之前于服务器上更新存储值,并且需要页面使用来自服务器的更新值进行水合的高级场景,请设置一个返回服务器状态的函数:ssr: () => serverState

// Value of store on server at time of SSR, passed to client somehow...
const profileFromServer = { name: 'A User' }

export const Header = () => {
  const profile = useStore($profile, {
    // On server, always use up-to-date store value (set `ssr` to `false`).
    // On client, set server value to avoid error on hydration.
    ssr: typeof window === 'object' && (() => profileFromServer)
  })

  // Server render uses store's current value. Client uses value from function
  // for hydration, then after hydration re-renders with the current value.
  return <header>{profile.name}</header>
}