如果有兴趣了解更多用法及 api ,点击此处解锁中文文档
是不是觉得 Redux 很难用?想用 Context 代替,但是你知道吗,Context 也有个很大的缺点:
那么试试 zustand 吧,当然你可以选择 mobx,
zustand 与 mobx 最大的差别在于:
state = {a: 1}update(){state = {a: 2}
}
state = {a: 1}update(){state.a++
}
hooks
作为消费状态的主要手段context provider
包裹你的应用程序react
上下文,引用更加灵活重新渲染的组件更少
store 更新操作相对更加可控
composition api
作为消费状态的主要手段,而不是 Vue.use 全局注入npm install zustand # or yarn add zustand
创建的 store 是一个 hook
,你可以放任何东西到里面:基础变量,对象、函数,状态必须不可改变地更新,set
函数合并状态以实现状态更新。
import { create } from 'zustand'const useBearStore = create((set) => ({bears: 0,increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),removeAllBears: () => set({ bears: 0 }),
}))
可以在任何地方使用钩子,不需要提供 provider
。
基于 selector
获取您的目标状态,组件将在状态更改时重新渲染。
function BearCounter() {const bears = useBearStore((state) => state.bears)return {bears} around here ...
}
function Controls() {const increasePopulation = useBearStore((state) => state.increasePopulation)return
}
什么,你还想试试在 Vue 中使用?那么 Step1 与 Step2 基本一致,不同的是 Step3 (Store 绑定组件):
npm install zustand-vue # or yarn add zustand-vue
创建的 store 是一个 hook
,你可以放任何东西到里面:基础变量,对象、函数,状态必须不可改变地更新,set
函数合并状态以实现状态更新。
import create from "zustand-vue";const useBearStore = create((set) => ({bears: 0,increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),removeAllBears: () => set({ bears: 0 }),
}))export default useBearStore
基于 selector
获取您的目标状态,组件将在状态更改时重新渲染。
Store 绑定组件在
vue3
与vue2
中有所不同。
store.bears: {{ bears }}