Zustand: typescript 订阅

1l5u6lss  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(195)

如何在typescript中使用subcribe方法?我收到错误Property 'subscribe' does not exist on type 'BearState'

//store.ts
import { create } from 'zustand'

interface BearState {
  bears: number
  increase: (by: number) => void
}

export const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}))
//App.tsx

function App() {
    const bearStore = useBearStore()
    const unsub = bearStore.subscribe(console.log)

    return (
        <div>
        </div>
    )
}

export default App
a64a0gku

a64a0gku1#

useEffect(() => {
    const unsubscribe = useBearStore.subscribe(
      (current, previous) => {
        // Do something with the updated state
        console.log('New state:', current);
      },
    );

    return () => {
        unsubscribe();
    }
});

相关问题