zustand 状态管理 使用小结

116 阅读1分钟

在nextjs中引入zustand,作状态管理

1、引用和创建

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 }),
}))

2、组件中使用

// 状态使用
function BearCounter() {
  const bears = useStore((state) => state.bears)
  return <h1>{bears} around here...</h1>
}
// 方法调用
function Controls() {
  const increasePopulation = useStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

3、非组件(非hooks)使用

const {bears} = useStore.getState()
console.log(bears)