useReducer 局限性,
不支持异步函数
不支持内部的 reducer 互相调用
不支持和其他 state 联动(比如要当参数穿进去才可用
性能优化、受控、action 互调、数据切片、状态调试
zustand 中,函数不用区分同步或者异步
zustand 的 useStore 出来的值或者方法,都是橙色的变量,具有稳定引用,不会造成不必要的重复渲染。
- get 方法直接拿到当前 store 中最新的 state 快照,获取最新值
- 数据分形在状态管理,子组件能够以同样的结构,作为一个应用使用,这样的结构就是分形
persist本地存储
实现本地持久化存储,刷新页面会自动将本地数据装载到 store中
import { devtools } from 'zustand/middleware';export const useBearStore = create(persist((set, get) => ({bears: 0,addABear: () => set({ bears: get().bears + 1 }),}),{// name of the item in the storage (must be unique)name: 'food-storage',// (optional) by default, 'localStorage' is usedstorage: createJSONStorage(() => sessionStorage),}));
zustand undoredo
状态派生
