在表单提交后显示 toast

Show toast after a form submit

我想提交一个表单,我想重新加载当前页面以便刷新表单,刷新后我想在 toast 中显示 Api 响应。当我注释掉 event.preventDefault() 时,它在重新加载后不显示吐司。当我使用 event.preventDefault() 并手动重新加载页面时,吐司工作正常!但我希望它自动刷新并显示吐司。这是我的代码,

    const handleAddUser = async (event) => {
    event.preventDefault();
    try {
      const result = await Http.post(apiEndPoint, {
        userRole: role,
        userEmail: userEmail,
        userPassword: userPassword,
        firstName: firstName,
        lastName: lastName,
        address: address,
      });
      localStorage.setItem("res", "success");
      localStorage.setItem("success", result.data);
      console.log("proper", props);
    } catch (ex) {
      localStorage.setItem("res", "err");
      localStorage.setItem("err", ex.response.data);
    }
  };

这是我的 useEffect 挂钩,

    useEffect(() => {
    const response = localStorage.getItem("res");
    const result = localStorage.getItem(response);
    if (response && response === "success") {
      toast.success(result);
      localStorage.removeItem("res");
    } else if (response && response === "err") {
      toast.error(result);
      localStorage.removeItem("res");
    }
  }, []);

这是因为如果您删除 event.preventDefault(),您的页面在有机会发送请求并设置到 localStorage

之前会重新加载

一个解决方案是保留 event.preventDefault() 并将 window.location.reload() 放在处理程序的末尾,如下所示:

const handleAddUser = async (event) => {
  event.preventDefault();
  try {
    const result = await Http.post(apiEndPoint, {
      userRole: role,
      userEmail: userEmail,
      userPassword: userPassword,
      firstName: firstName,
      lastName: lastName,
      address: address,
    });
    localStorage.setItem("res", "success");
    localStorage.setItem("success", result.data);
    console.log("proper", props);
  } catch (ex) {
    localStorage.setItem("res", "err");
    localStorage.setItem("err", ex.response.data);
  }
  window.location.reload();
};