lui*_*ina 7 javascript typescript reactjs react-hooks use-reducer
问候,我在 typeStript 应用程序中实现 useReducer 时遇到了一些麻烦,我有几个错误(所有这些错误都在减速器上),但这是应用程序中最常见的一个,每次我调用调度函数时它都会跳转错误“预期有 0 个参数,但得到了 1”
这就是reducer的功能
interface Edit {
id?: number;
todo?: string;
}
type Actions =
{ type: "add"; payload: string }
| { type: "remove"; payload: number }
| { type: "done"; payload: number }
| { type: "all"; payload: Todo[] }
| { type: "edit"; payload: Edit };
const reducerFunction = (state: Todo[], actions: Actions) => {
const todoActions = {
add: [...state, { id: Date.now(), todo: actions.payload, isDone: false }],
edit: state.map((todo) =>
todo.id === actions.payload.id
? { ...todo, todo: actions.payload.todo }
: todo
),
remove: state.filter((todo) => todo.id !== actions.payload),
done: state.map((todo) =>
todo.id === actions.payload ? { ...todo, isDone: !todo.isDone } : todo
),
all: state = actions.payload
};
return todoActions[actions.type] ?? state;
};
Run Code Online (Sandbox Code Playgroud)
减速器和其中一个调度器
const [todos, dispatch] = useReducer(reducerFunction, []);
/*-----------*/
dispatch({ type: "add", payload: todo });
Run Code Online (Sandbox Code Playgroud)
您可以在此codesanbox中观看整个应用程序: https://codesandbox.io/s/trello-todo-component-clone-ebpqw4 ?file=/src/App.tsx:1465-1507
Ant*_*ton 16
为了让 TypeScript 推断出状态的类型,您需要向reducerFunction.
const reducerFunction = (state: Todo[], actions: Actions): Todo[]
Run Code Online (Sandbox Code Playgroud)
或者,您可以将 的类型添加reducerFunction到useReducer调用中。
const [todos, dispatch] = useReducer<(state: Todo[], actions: Actions) => Todo[]>(reducerFunction, []);
Run Code Online (Sandbox Code Playgroud)