表单提交后自动重载页面并展示API响应toast的实现问题
问题根因
- 注释
event.preventDefault()时,表单会触发默认提交逻辑立即重载页面,此时异步API请求还未执行完成,响应结果还没写入localStorage,重载后读不到对应内容自然无法弹出toast - 保留
event.preventDefault()时没有主动触发页面重载,只有手动刷新才会触发useEffect读取存储内容展示toast
修复方案
保留原useEffect逻辑不变,仅修改表单提交函数,等API请求完成(无论成功失败)后主动触发页面重载即可,修改后代码如下:
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"); // 注意:如果result.data是对象类型,需要转成字符串存储:localStorage.setItem("success", JSON.stringify(result.data)) localStorage.setItem("success", result.data); } catch (ex) { localStorage.setItem("res", "err"); // 同上,ex.response.data为对象时需JSON.stringify处理 localStorage.setItem("err", ex.response.data); } finally { // 接口请求完成后主动重载页面,保证localStorage已写入完成 location.reload(); } };
补充说明
如果你的API返回内容是对象类型,读取的时候需要对应解析,优化后的useEffect逻辑如下:
useEffect(() => { const response = localStorage.getItem("res"); if (!response) return; const result = JSON.parse(localStorage.getItem(response)); if (response === "success") { toast.success(result); } else if (response === "err") { toast.error(result); } // 用完清理所有相关存储项避免冗余 localStorage.removeItem("res"); localStorage.removeItem(response); }, []);
内容的提问来源于stack exchange,提问作者Saadi
相关产品推荐
相关产品推荐

