【发布时间】:2020-06-13 21:20:26
【问题描述】:
我在数据操作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');
});
有什么建议吗?
【问题讨论】:
-
我认为您输入了错误的函数名称。 props.enrollStudent 应该是 props.EnrollStudent。至少这个函数在定义中是这样出现的。
-
@i.brod 感谢您的评论。我在
mapDispatchToProps方法中将它重命名为enrollStudent。我更新了我的代码。 -
它有效吗..?
-
@i.brod 没有
.then它可以工作。 -
所以
EnrollStudent()是一个返回函数的函数...
标签: reactjs redux promise react-redux dispatch