我在数据操作tsx
文件中具有以下方法:
export function EnrollStudent(student, courseId) {
return dispatch => {
dispatch(enrollUserBegin());
axios
.post("api/Course/EnrollStudent/" + courseId + "/" + student.id)
.then(response => {
if (response.data === 1) {
dispatch(enrollUserSuccess(student, courseId));
console.log("Student is enrolled.");
toast.success("Student is enrolled successfully.", {
position: toast.POSITION.TOP_CENTER
});
} else {
dispatch(enrollUserSuccess(null, 0));
console.log("Failed to enroll.");
toast.warn(
"Failed to enroll the student. Possible reason: Already enrolled.",
{
position: toast.POSITION.TOP_CENTER
}
);
}
})
.catch(error => {
dispatch(enrollUserFailure(error));
toast.warn("An error occurred. Please contact the Admin.", {
position: toast.POSITION.TOP_CENTER
});
});
};
}
通过单击按钮从另一个组件调用此方法:
const enroll_onClick = e => {
e.preventDefault();
const currentUserId = authenticationService.currentUserValue["id"];
var student: any = { id: currentUserId };
props.enrollStudent(student, st_courseId);
};
const mapDispatchToProps = dispatch => {
return {
enrollStudent: (student, courseId) => dispatch(EnrollStudent(student, courseId)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(CourseEnrollmentWithCode);
这很好,并且数据库已正确更新。但是,我想获取enrollStudent
的结果并执行一个操作(例如,导航到另一页)。
我尝试了这个,但是收到了props.enrollStudent() is undefined
错误。
props.enrollStudent(student, st_courseId)
.then(() => {
console.log("enrolld");
history.push('/courses');
});
有什么建议吗?
您不得在动作创建者中使用承诺 ...您只能返回动作对象... https://redux.js.org/api/store/
在这种情况下(副作用)您必须使用中间件([redux-thunk
,redux-promise
,redux-saga
)... https://redux.js.org/api/applymiddleware/
如果未使用中间件...当前行为(看起来部分起作用)是至少误导。