【问题标题】:How to send the errors in Action(Redux) to the Frontend(React)?如何将 Action(Redux) 中的错误发送到 Frontend(React)?
【发布时间】:2021-11-02 11:42:28
【问题描述】:

所以我正在构建一个具有登录功能的 MERN 堆栈应用程序。每当用户发送错误的凭据时,我都会通过res.json({errorMessage: 'sample'}) 引发错误。但是,我还在我的应用程序中实现了 Redux,并且我有一个看起来像这样的操作。

export const loginUser =
  ({ email, password }) =>
  async (dispatch) => {
    try {
      const { data } = await axios.post("http://localhost:5000/auth/login", {
        email,
        password,
      });

      dispatch({ type: "LOGIN_USER", payload: data });
    } catch (error) {
      console.log("Err", error.response.data.errorMessage);
    }
  };

我在操作中收到错误消息,但我想在 React 中显示它。我正在尝试以这种方式访问​​它,但它不起作用。

const handleSubmit = (e) => {
    e.preventDefault();

    try {
      dispatch(loginUser({ email, password }));
    } catch (error) {
      console.log(error.response.data.errorMessage);
    }
  };

我在操作中而不是在我的前端中收到错误。如何在我的前端获取 errorMessage?提前致谢。

【问题讨论】:

    标签: node.js reactjs redux redux-thunk


    【解决方案1】:

    你应该在loginUser的catch中添加抛出错误

    export const loginUser =
      ({ email, password }) =>
      async (dispatch) => {
        try {
          const { data } = await axios.post("http://localhost:5000/auth/login", {
            email,
            password,
          });
    
          dispatch({ type: "LOGIN_USER", payload: data });
        } catch (error) {
          console.log("Err", error.response.data.errorMessage);
          throw error
        }
      };
    

    并将handleSubmit 更改为async

      const handleSubmit = async (e) => {
        e.preventDefault();
    
        try {
          await dispatch(loginUser({ email, password }));
        } catch (error) {
          console.log(error.response.data.errorMessage);
        }
      };
    

    【讨论】:

    • 我添加了它,但不幸的是,它给了我一个错误。
    • 天哪,它成功了!感谢您的帮助。我真的很感激!
    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2023-03-26
    • 2018-09-03
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2016-08-16
    • 2023-03-04
    相关资源
    最近更新 更多