全局状态管理 zustand
Zustand 是一个 轻量级、直观的 React 状态管理库,由 Poimandres 团队 开发,作者也参与了著名的 react-three-fiber 等项目。Zustand 的设计目标是简单、灵活,并避免了 React 组件间复杂的状态传递和性能问题。
🧪 基础使用示例
import React from 'react';
import { useGlobalStore } from '@/store';
import { prevState } from '@/store/init';
function Index() {
const theme = useGlobalStore((state) => state.theme);
//框架内自定义函数 可以同时设置多个状态
const setState = useGlobalStore((state) => state.setState);
useEffect(() => {
//根据业务设置状态值
setState({ theme: 'dark' });
//出现多层级属性赋值时 需要使用回调函数形式赋值
setState((state) => {
state.obs.ws = '127.0.0.1';
});
}, []);
//初始化
useLayoutEffect(() => {
//初始化预设状态
setState({ ...prevState });
}, []);
return <div>{theme}</div>;
}
🧪 Action
如果同一个接口很多组件内都需要调用,那么只需在 zustand 内定义一次即可灵活调用。
📚 定义 src/store/index.ts
import { message } from "@itera-web/utils-message";
import { requestChatList } from "@/services/public";
// 创建 Zustand Store,并添加持久化功能
export const useGlobalStore = create<GlobalState & GlobalActions>()(
persist(
immer((set) => ({
...baseState,
// 异步获取聊天列表
fetchChatList: async () => {
try {
const res = await requestChatList();
const historyDialogList = res.data?.map((item: any, index: number) => ({
...item,
key: `${Math.floor(Math.random() * 1000000000)}-${index}`,
data: item.data?.map((el: any) => ({ ...el, active: false }))?.reverse(),
}));
set({ historyDialogList });
} catch (err) {
console.error('fetchChatList error:', err);
}
},
})),
),
);
📚 组件内使用示例
import React from 'react';
import { useGlobalStore } from '@/store';
function Index() {
const historyDialogList = useGlobalStore((state) => state.historyDialogList);
const fetchChatList = useGlobalStore((state) => state.fetchChatList);
useEffect(() => {
fetchChatList().then();
}, []);
return (
<div>
{/* 渲染 fetchChatList 获取的结果状态 */}
{historyDialogList}
</div>
);
}
✨ 使用说明
- 初始状态:
export const state用户第一次进入页面的默认值 - 预设状态:
export const prevState每次刷新页面的预定义值
清除缓存就是要把状态还原为初始状态,在清除缓存时可以指定忽略的还原的状态 key。
src/store/index.ts
//向数组内添加不参与缓存清理的状态
const noClearState = ['token'];
🧬 Zustand 适用场景
- 替代 Redux/Context,简化全局状态管理
- 用于组件之间共享状态(如弹窗状态、用户信息)
- 多 store 管理(更灵活的模块化结构)