下面是 CreateCoursePage 组件,我在其中使用react-redux 来管理一些数据库操作后的状态。然而
dispatch(CreateCourse(course)
中的 mapDispatchToProps
语句会抛出此异常: TS2345 (TS) Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'.
interface CreateCourseProps {
error: string;
createCourse: (course: Course) => ReturnType<typeof CreateCourse>;
}
const CreateCoursePage: React.FC<CreateCourseProps> = ({ createCourse }) => {
const onSubmit = (course: Course) => {
createCourse(course);
};
return (
//other code
);
};
const mapStateToProps = (state: any) => ({
error: state.courseReducer.error
})
const mapDispatchToProps = (dispatch: Dispatch) => ({
createCourse: (course: Course) => dispatch(CreateCourse(course)),
});
const ConnectedCreateCourse = connect(mapStateToProps, mapDispatchToProps)(CreateCoursePage);
export default ConnectedCreateCourse;
下面是 DataOperations.tsx 中定义的 CreateCourse 函数:
export function CreateCourse(course: CourseData) {
return async (dispatch: Dispatch) => {
dispatch(CourseDopStarted());
axios({
method: 'post',
url: 'api/Course/CreateCourse',
data: course
}).then(response => {
console.log('Course is created.');
dispatch(CreateCourseSuccess(response.data as CourseData));
toast.success("Course is created successfully!", {
position: toast.POSITION.TOP_CENTER
});
})
.catch(error => {
dispatch(CourseDopFailed(error))
});
}
}
添加
as any
(dispatch(CreateCourse(course) as any
) 可以解决这个问题,但这在 TS 中不是一个好的做法。我找到了一些解决方案,但无法将它们与我自己的案例联系起来。我感谢任何帮助!
我认为因为你在CreateCourse函数中使用了axios,并且axios函数是异步类型,所以你的函数类型为Promise。所以试试这个:
export function CreateCourse(course: CourseData) {
return async (dispatch: Dispatch): Promise<void> => {
// your code...
}
}