Skip to content

zustand

getting started

typescript
import { create } from 'zustand'

const useStore = create((set) => ({
    bears: 0,
    increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
    removeAllBears: () => set({ bears: 0 }),
    updateBears: (newBears) => set({ bears: newBears }),
}))
typescript
function BearCounter() {
  const bears = useStore((state) => state.bears)
  return <h1>{bears} bears around here...</h1>
}

function Controls() {
  const increasePopulation = useStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

immer

深层次属性合并

ts
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

interface User {
    gourd: {
        oneChild: string
        twoChild: string
        threeChild: string
        fourChild: string
        fiveChild: string
        sixChild: string
        sevenChild: string
    }
    updateGourd: () => void
}
//注意结构发生了变化!!!
const useUserStore = create<User>()(
    immer((set) => ({
        //创建葫芦娃
        gourd: {
            oneChild: '大娃',
            twoChild: '二娃',
            threeChild: '三娃',
            fourChild: '四娃',
            fiveChild: '五娃',
            sixChild: '六娃',
            sevenChild: '七娃',
        },
        updateGourd: () =>
            set((state) => {
                state.gourd.oneChild = '大娃-超进化' //这儿不需要状态合并了需要修改什么值直接改就行了
                state.gourd.twoChild = '二娃-谁来了'
                state.gourd.threeChild = '三娃-我来了'
            }),
    }))
)

export default useUserStore

use-shallow

useShallow 只检查顶层对象的引用是否变化,如果顶层对象的引用没有变化(即使其内部属性或子对象发生了变化,但这些变化不影响顶层对象的引用),使用 useShallow 的组件将不会重新渲染

ts
import { useShallow } from 'zustand/react/shallow'

const { rap, name } = useUserStore(
    useShallow((state) => ({
        rap: state.hobby.rap,
        name: state.name,
    }))
)