主题
简介
¥Introduction
小型、快速且可扩展的 bearbones 状态管理解决方案。Zustand 有一个基于钩子的舒适 API。它不是样板或有态度,但有足够的惯例来明确和流动。
¥A small, fast, and scalable bearbones state management solution. Zustand has a comfy API based on hooks. It isn't boilerplatey or opinionated, but has enough convention to be explicit and flux-like.
不要因为它很可爱而忽视它,它有爪子!花了很多时间来处理常见的陷阱,比如混合渲染器之间可怕的 僵尸子问题、React 并发 和 上下文丢失。它可能是在 React 空间中唯一一个正确完成所有这些的状态管理器。
¥Don't disregard it because it's cute, it has claws! Lots of time was spent to deal with common pitfalls, like the dreaded zombie child problem, React concurrency, and context loss between mixed renderers. It may be the one state manager in the React space that gets all of these right.
你可以尝试现场演示 此处。
¥You can try a live demo here.
安装
¥Installation
Zustand 可作为 NPM 上的包使用:
¥Zustand is available as a package on NPM for use:
bash
# NPM
npm install zustand
# Or, use any package manager of your choice.
首先创建一个存储
¥First create a store
你的存储是一个钩子!你可以将任何东西放入其中:原始、对象、函数。set
函数合并状态。
¥Your store is a hook! You can put anything in it: primitives, objects, functions. The set
function merges state.
js
import { create } from 'zustand'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
updateBears: (newBears) => set({ bears: newBears }),
}))
然后绑定你的组件,就这样!
¥Then bind your components, and that's it!
你可以在任何地方使用钩子,而无需提供程序。选择你的状态,当该状态发生变化时,使用组件将重新渲染。
¥You can use the hook anywhere, without the need of providers. Select your state and the consuming component will re-render when that state changes.
jsx
function BearCounter() {
const bears = useStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}