【问题标题】:Is there any way to define two states inside Axios .catch method?有没有办法在 Axios .catch 方法中定义两个状态?
【发布时间】:2022-11-20 07:49:51
【问题描述】:

我正在尝试更新 axios.post 方法中的两个状态,但是在尝试通过单击登录按钮登录时,页面变为空白,当我评论或删除其中一个状态时,即 setEmptyFields(error.response.data.emptyFields) 或 setError(error. response.data.message) 它可以工作但是同时使用它没有任何方法来处理这个问题?

const response = await axios
      .post("http://localhost:4000/api/auth/login", loginUser)
      .catch((error) =>
        setEmptyFields(error.response.data.emptyFields)
        setError(error.response.data.message)
      );

【问题讨论】:

  • 通常你只会使用一种状态。控制台中的错误消息会告诉您到底哪里出错了。设置 2 个状态也可以。我总是在我的 .catch 中设置加载和错误,所以我 100% 确定

标签: reactjs post react-hooks axios mern


【解决方案1】:

如果您使用 await 关键字,请使用 try/catch


try {
  const response = await axios.post("http://localhost:4000/api/auth/login", loginUser)
  //do something with the response...
} catch(error) {
  setEmptyFields(error.response.data.emptyFields)
  setError(error.response.data.message)
}

或者,您可以使用 then 来处理响应:

axios
  .post("http://localhost:4000/api/auth/login", loginUser)
  .then((response) => {
    //do something with the response...
  })
  .catch((error) =>
    setEmptyFields(error.response.data.emptyFields)
    setError(error.response.data.message)
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多