前言
本文帮助有一定基础的同学快速在项目里面引入zustand,提供最佳实践
一、安装
yarn add zustand
二、新建store相关文件
-src
- store
- index.ts
- dict.ts
三、index.ts
import { useShallow } from 'zustand/react/shallow';
import { BaseDictState, DictAction, useDictStore } from './dict';
export const useDictStoreWithKey = <
K extends keyof (BaseDictState & DictAction),
>(
keys: K[],
) =>
useDictStore(
useShallow((state) => { // 解决频繁组件更新
const newStates: Partial<Pick<BaseDictState & DictAction, K>> = {};
// 挑选(过滤)我们需要的属性,避免引发组件更新
keys.forEach((key) => {
newStates[key] = state[key];
});
return newStates as Pick<BaseDictState & DictAction, K>;
}),
);
四、dict.ts
import { create } from 'zustand';
const sleep = (ms: number = 1000) =>
new Promise((reslove) => {
setTimeout(() => {
reslove(0);
}, ms);
});
export type BaseDictState = {
userInfo: any;
count: number;
};
export const initState: BaseDictState = {
userInfo: {},
count: 0,
};
export type DictAction = {
setUserInfo: (userInfo: any) => void;
addCount: () => void;
delayAddCount: () => Promise<void>;
};
export const useDictStore = create<BaseDictState & DictAction>((set, get) => {
return {
...initState,
setUserInfo: (userInfo: any) => {
set({ userInfo });
},
addCount: () => {
// 同步逻辑
set({ count: get().count + 1 });
},
delayAddCount: async () => {
// 异步逻辑
await sleep(1000);
get().addCount();
},
};
});
五、React组件使用
import { useDictStoreWithKey } from '@/store';
import { Button } from 'antd';
const TestPage = () => {
const { count, delayAddCount, addCount } = useDictStoreWithKey([
'userInfo',
'count',
'addCount',
'delayAddCount',
]);
return (
<div>
welcome{count}
<Button onClick={() => delayAddCount()}>delayAddCount</Button>
<Button onClick={() => addCount()}>addCount</Button>
</div>
);
};
export default TestPage;
六 结语
感谢看到这里,点赞收藏关注来一波,持续提供最佳干货实践!!!