react状态管理zustand

1,095 阅读1分钟

最近看到zustand这个状态管理库,觉得使用起来很不错。经过一段时间zustand的使用,分享下自己使用时一些小技巧。

仓库地址

zustand

wiki

官方使用文档

下载使用

npm install zustand

新建store.ts

// store.ts
import create from 'zustand'
// 创建store
const useStore = create(() => ({ count: 0 }))

// 更改store中状态
export const actionCount = () => {
    useStore.setState({ count: 0 });
    // 或者
    useStore.setState((prev) => ({ count: prev.count + 1 }));
    // 或者
    useStore.setState({ count: useStore.getState().count + 1 });
}

新建A.tsx 和 B.tsx

// A.tsx
const A = () => {
    const { count } = useStore((state) => (state.count));
    return <div>{count}</div>
}

// B.tsx
import { actionCount } from 'store.ts'
const B = () => {
    return <button onClick={actionCount}>add count</button>
}

计算属性

修改useStore代码

const useStore = create((get) => ({
    count: 0, computed: {
        get doubleCount() {
            return get().count * 2
            // 或者
            return useStore.getState().count * 2;
        }
    }
}))