首页 > 解决方案 > Redux 动作和模态窗口

问题描述

我有一个调用 api 并返回一个对象的 redux 操作。配置文件对象(如果成功执行)或错误对象(如果不成功)。除了一件事,一切都很好。我通过模式窗口发送数据。如果一切正常,我只是重新加载页面,如果没有,我不想重新加载页面,我想显示错误。行动:

export const addEducation = (eduData, history) => dispatch => {
  axios
    .post("/api/profile/education", eduData)
    .then(window.location.reload())
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
}; 

接口:

router.post(
  "/education",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validateEduInput(req.body);

    //Check validation
    if (!isValid) {
      return res.status(400).json(errors);
    }
    Profile.findOne({ user: req.user.id }).then(profile => {
      const newEdu = {
        school: req.body.school,
        degree: req.body.degree,
        fieldOfStudy: req.body.fieldOfStudy,
        from: req.body.from,
        to: req.body.to,
        current: req.body.current,
        description: req.body.description
      };

      //Add to exp array
      profile.education.unshift(newEdu); //Add the education to the beginning of the array opposed to push
      profile
        .save()
        .then(profile => res.json(profile))
        .catch(err => res.status(404).json(err));
    });
  }
);

正如您在 API 代码中看到的,我验证接收到的输入,如果没有通过则返回错误对象。现在,redux 操作以任何一种方式重新加载页面。我应该如何检查我是否有错误并防止页面在 .then 函数中重新加载?

标签: javascriptreactjsreduxreact-redux

解决方案


从代码中,我无法破译任何错误。也许,您也可以尝试绑定 .then 响应:

然后(() => window.location.reload())

此外,尝试调试或记录响应以检查错误情况下的状态代码。


推荐阅读