【问题标题】:Returning the result from dispatch to a component throws "undefined" exception将调度结果返回给组件会引发“未定义”异常
【发布时间】: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


【解决方案1】:

你不能在动作创建者中使用承诺 ...你只能返回一个动作对象...https://redux.js.org/api/store/

在这种情况下(副作用)你必须使用中间件redux-thunkredux-promiseredux-saga)...https://redux.js.org/api/applymiddleware/

如果未使用中间件...当前行为(看起来部分工作)至少会误导

【讨论】:

  • 鉴于提供的代码,他肯定在使用 redux-thunk 中间件。
【解决方案2】:

通过查看代码,我猜您正在使用redux-thunk 中间件。

EnrollStudent 函数中,您必须在axios(第5 行)之前添加一个return 语句,以便您的thunk 函数(EnrollStudent 返回的函数)返回一个promise。

看看这里的例子:https://github.com/reduxjs/redux-thunk,尤其是makeASandwichWithSecretSauce函数。

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多