React中使用Zustand时出现set.getState is not a function错误求助
问题解决:Zustand中"set.getState is not a function"错误
你遇到的错误是因为Zustand的set函数本身没有getState方法,你错误地通过set.getState()去获取当前状态了。另外你的handleAddItem方法还存在参数混淆的问题,一起给你修正:
关键修改点
- 添加
get参数:Zustand的create回调函数默认提供两个参数set和get,get方法才是用来获取当前状态的,所以要把(set)改成(set, get)。 - 替换状态获取方式:用
get()替代set.getState()来获取当前的toDoList。 - 修正事件参数:你在
handleAddItem里调用了title.preventDefault(),说明参数应该是事件对象,不是标题文本,这里要修正参数名,并从store的newItem中获取输入的标题内容。
修正后的完整代码
import {create} from 'zustand'; const useTodoStore = create((set, get) => ({ // 添加get参数 toDoList: [], newItem: '', // Input value for new item // Fetch data fetchTodos: async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos'); const todos = await response.json(); set({ toDoList: todos }); } catch (error) { console.error('Error fetching todos:', error); } }, // Actions for updating state handleAddItem: (e) => { // 参数改为事件对象e e.preventDefault(); const { toDoList, newItem } = get(); // 用get()获取当前状态 if (!newItem.trim()) return; // 空内容不添加 const newId = toDoList.length ? Math.max(...toDoList.map((todo) => todo.id)) + 1 : 1; // 处理空数组的情况 const newTodoItem = { id: newId, title: newItem, completed: false }; set({ toDoList: [...toDoList, newTodoItem], newItem: '' }); }, handleToggleCompleted: (id) => set((state) => ({ toDoList: state.toDoList.map((todo) => todo.id === id ? { ...todo, completed: !todo.completed } : todo ), })), setNewItem: (value) => set({ newItem: value }), })); export default useTodoStore;
额外说明
- 当你需要基于当前状态更新时,除了用
get()获取状态,也可以像handleToggleCompleted那样,给set传递一个接收当前state的函数,两种方式都可行。 - 加了空内容判断,避免添加空的待办项;同时处理了
toDoList为空时的ID生成逻辑,防止Math.max报错。
内容的提问来源于stack exchange,提问作者Emmanuel Guerrero Hernandez
相关产品推荐
相关产品推荐

