实现reducer时状态类型怎么做?我有属性和功能。
export interface State {
form: boolean;
errorForm: boolean;
projects: ProjectI[];
project: ProjectI;
showFormFn(): void;
getProjectsFn(): void;
addProjectFn(project: ProjectI): void;
showErrorFn(): void;
currentProjectFn(projectId: string): void;
deleteProjectFn(projectId: string): void;
}
但是我在使用钩子和尝试初始化状态时遇到了问题。什么是正确的实施方式?
答案 0 :(得分:0)
这是一种以经典方式实现它的方法:
interface ProjectI {
id: string;
}
export interface State {
form: boolean;
errorForm: boolean;
projects: ProjectI[];
project: ProjectI;
showFormFn(): void;
getProjectsFn(): void;
addProjectFn(project: ProjectI): void;
showErrorFn(): void;
currentProjectFn(projectId: string): void;
deleteProjectFn(projectId: string): void;
}
type Actions = { type: 'addProject', payload: ProjectI } | { type: 'setProject', payload: ProjectI } | { type: 'error' }
function reducer(state: State, action: Actions) {
switch (action.type) {
case 'addProject':
return { ...state, projects: state.projects.concat(action.payload) };
case 'setProject':
return { ...state, project: action.payload };
case 'error':
return { ...state, errorForm: true };
default:
return state;
}
}
TS Playground 从这里显示打字稿中存在的类型。