如何在 React 中进行状态管理?使用 Zustand!

目录

计数器

import { create } from 'zustand'

const useStore = create(set => ({
  count: 1,
  inc: () => set(state => ({ count: state.count + 1 })),
}))

function Controls() {
  const inc = useStore(state => state.inc)
  return <button onClick={inc}>one up</button>
}

function Counter() {
  const count = useStore(state => state.count)
  return <h1>{count}</h1>  
}

用法

创建状态 state 操作 action

Basic typescript usage doesn’t require anything special except for writing create<State>()(...) instead of create(...)

import { create } from 'zustand'

interface BearState {
  bears: number
  increase: (by: number) => void
}

const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}))

const useFishStore = create((set) => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({}, true), // clears the entire store, actions included
  deleteTuna: () => set((state) => omit(state, ['tuna']), true),
}))

const useSoundStore = create((set, get) => ({
  sound: "grunt",
  action: () => {
    const sound = get().sound  // you still have access to state outside of it through get
    // ...
  }
})

export default useBearStore

在 react 之外使用呢?

import { createStore } from 'zustand/vanilla'

const store = createStore(() => ({ ... }))
const { getState, setState, subscribe } = store

export default store

import { useStore } from 'zustand'
import { vanillaStore } from './vanillaStore'

const useBoundStore = (selector) => useStore(vanillaStore, selector)

获取状态

// It will cause the component to update on every state change!
const state = useBearStore()

// It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
const bears = useBearStore((state) => state.bears)

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useBearStore(
  (state) => ({ nuts: state.nuts, honey: state.honey }),
  shallow
)

// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useBearStore(
  (state) => [state.nuts, state.honey],
  shallow
)

// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useBearStore((state) => Object.keys(state.treats), shallow)

// You may provide any custom equality function
const treats = useBearStore(
  (state) => state.treats,
  (oldTreats, newTreats) => compare(oldTreats, newTreats)
)
const increase = useBearStore((state) => state.increase)

在组件之外如何使用?

const useDogStore = create(() => ({ paw: true, snout: true, fur: true }))

// Getting non-reactive fresh state
const paw = useDogStore.getState().paw
// Listening to all changes, fires synchronously on every change
const unsub1 = useDogStore.subscribe(console.log)
// Updating state, will trigger listeners
useDogStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()

// You can of course use the hook as you always would
const Component = () => {
  const paw = useDogStore((state) => state.paw)
  ...

参考文章

Zustand

https://github.com/pmndrs/zustand

标签 :
comments powered by Disqus

相关文章

BlockSuite 一款 Block Style 的编辑器,仅仅是编辑器!

先说结论 我的博客不太适合用 BlockSuite 作为编辑器,因为: 不知道如何渲染,我可以编辑,但是如何展示给匿名用户看? SEO 不太明确,也想着转成 HTML 来做,但是成本太高? 其他博主的调研:https://blog.nineya.com/archives/154.html 开始! 学习一下:https://block-suite.com/ Scratch(QuickStart) 简单安装一下,目前是 canary 版本, AFFiNE 也是用的这个版本,每次都打包的 master 分支,基本上每天都有更新。

阅读更多
我用过的觉得好用的软件、工具、网站等的推荐

最初是我重置了系统,然后发现过去的习惯都要重新来一遍,于是为什么不写一篇文章呢? 比如,macOS 上可以一键安装我需要的软件: brew install --cask microsoft-edge calibre sogouinput mos snipaste iina iterm2 rectangle 后来,延伸到我用过的一些在线工具,比如作图、汇率转换等。 于是,这篇文章主要用于推荐软件、浏览器插件、在线工具、网站等。

阅读更多
Snapcast 多房间音频控制一体化

动机 想要手头的两台 MBP 能同时无延迟播放音频,拒绝使用直播流的形式。 Tip update at 2025-04-13

阅读更多