在按钮上发起 POST 请求后重定向

时间:2021-05-13 10:16:22

标签: reactjs react-redux react-router

我制作了一个注册表单,并根据成功/不成功的注册希望在用户单击按钮并收到服务器的响应后将用户重定向到带有通知的页面。如果注册成功,路由为"register/success",否则为"register/error"

当点击按钮时,我通过 axios 发送请求:

<Button
 type="submit"
      onClick={() => {
            sendCreateAccountRequest(
              fullName,
              email,
              password,
              confirmingPassword
            );
          }}
>Create Account</Button>

被调用的函数:

export const sendCreateAccountRequest = (fullName, email, password) => {
  const obj = { fullName, email, password }
  axios
    .post(url.registerUrl, obj)
    .then(response => {
      if (response.status === 200 || response.status === 204) {
        return true
      }
    })
    .catch(err => {
      if (err.response) {
        return err.message
      }
      if (err.request) {
        return "There are some server troubles"
      }
    })
}

我正在考虑使用 useHistory 钩子,但调用的函数是纯 JS 并且没有反应。 同样,我想让 Redux 参与其中,但没有找到在组件之外使用它的方法。

在相应的路由上提交表单后如何重定向用户?为此,我应该使用什么方法?

1 个答案:

答案 0 :(得分:1)

您可以从 catch 中删除 sendCreateAccountRequest 块并在组件级别处理错误:


const history = useHistory();

const handleClick = async () => {
    try {
        await sendCreateAccountRequest(
              fullName,
              email,
              password,
              confirmingPassword
            );
        history.push('register/success');
     } catch (e) {
       // handle error here
       history.push('register/error');
     }
}
(...)

<Button type="submit"onClick={handleClick}>Create Account</Button>

但是,如果您想在组件外部委托该逻辑,您应该查看 https://redux-toolkit.js.org/ 库及其示例。