NextJs中Zustand persist调用clearStorage出现TypeError问题求助
解决Zustand persist的clearStorage调用报错问题
错误原因
你直接通过useItemsStore.persist访问persist方法是错误的——Zustand中被persist包装后的store,persist属性并不挂载在useItemsStore这个hook函数本身,而是挂载在调用hook后返回的store实例上。直接访问函数的persist属性会得到undefined,自然无法读取clearStorage方法。
正确解决方案
方案1:在组件内获取store实例后调用
import { useItemsStore } from '@/stores/itemsStore' import { Button } from '@/components/ui/button' export default function StateInput() { // 调用hook获取store实例 const itemsStore = useItemsStore() const clearStorage = () => { // 从实例的persist属性调用clearStorage itemsStore.persist.clearStorage() } return ( <Button className='destructive-color' onClick={clearStorage}> Clear Storage </Button> ) }
方案2:直接在onClick中通过getState调用
如果不想额外声明函数,也可以用Zustand的getState方法直接获取store实例:
<Button className='destructive-color' onClick={() => useItemsStore.getState().persist.clearStorage()} > Clear Storage </Button>
确认你的store创建方式
确保你的store是用persist正确包装的,示例如下:
// stores/itemsStore.ts import { create } from 'zustand' import { persist } from 'zustand/middleware' export const useItemsStore = create( persist( (set, get) => ({ items: [], addItem: (item) => set({ items: [...get().items, item] }), // 其他store方法 }), { name: 'items-storage', // localStorage存储的key } ) )
内容的提问来源于stack exchange,提问作者Russo
相关产品推荐
相关产品推荐

