前端潮流技术必须得狠狠跟上步伐,下面介绍 zustand(React)文档
什么是 zustand
来着官方的解释:基于 Flux 模型实现的小型、快速和可扩展的状态管理解决方案,拥有基于 hooks 的舒适的API,非常地灵活且有趣.
不要因为它很娇小就忽略它,它拥有锋利的爪子,花费了大量时间用来处理常见的陷阱,比如出现在多个复杂渲染器之间的 zombie child、react concurrency、以及 context loss 问题. Zustand 可以作为 React 应用中的一个状态管理器来正确处理这些问题。
对比其他状态管理框架
为什么是 zustand 而不是 redux?
- 轻巧灵活
- 将
hooks作为消费状态的主要手段 - 不需要使用
context provider包裹你的应用程序 - 可以做到瞬时更新(不引起组件渲染完成更新过程)
为什么是 zustand 而不是 react Context?
- 不依赖
react上下文,引用更加灵活 - 当状态发生变化时
重新渲染的组件更少 - 集中的、基于操作的状态管理
一个字香,两个字灵活,四个字使用简单~这不是是我们前端所需要的东西吗?对就是它了,盘它~~~
安装
# npm or yarn 的方式
npm install zustand # or yarn add zustand
## pnpm 方式
pnpm add zustand
创建store.ts or store.js
import { create } from 'zustand'
const useStore = create((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}))
export default useStore
基础使用
import useStore from './useStore';
function App() {
const { count, increase, decrease } = useStore();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</div>
)
}
export default App
ok,完毕搞定 zustand 的基础使用 是不是不到三分钟你就学会了?其实和 Vue生态pinia很接近相似用法~接下来继续介绍它的用法:
在多个组件中共享状态
你可以在多个组件中访问同一个 store,例如:
// ComponentA
import React from 'react';
import useStore from './useStore';
const ComponentA = () => {
const count = useStore((state) => state.count);
return <div>Component A Count: {count}</div>;
};
// ComponentB
import React from 'react';
import useStore from './useStore';
const ComponentB = () => {
const increase = useStore((state) => state.increase);
return <button onClick={increase}>Increase from Component B</button>;
};
// App.jsx
import React from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
function App() {
return (
<div>
<ComponentA />
<ComponentB />
</div>
);
}
export default App;
订阅状态
你可以选择性地订阅状态,如果只需要某些状态,可以像这样使用:
// 在组件中使用 Selector
const count = useStore((state) => state.count);
这样,只有 count 发生变化时,组件才会重新渲染。
中间件
Zustand 也支持中间件,你可以用来扩展 store 的功能,比如日志记录或持久化:
import create from 'zustand';
import { devtools } from 'zustand/middleware';
const useStore = create(devtools((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
})));
使用异步操作
你可以在 store 中处理异步操作,比如从 API 获取数据:
const useStore = create((set) => ({
data: [],
fetchData: async () => {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
set({ data: result });
},
}));
在组件中,你可以调用 fetchData 方法来获取数据:
import React, { useEffect } from 'react';
import useStore from './useStore';
function DataComponent() {
const { data, fetchData } = useStore();
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
好了,现在你应该可以单独使用 zustand 开发react项目了 ~