reactjs - 如何阻止页面刷新和丢失用户对不成功的发布请求的输入
问题描述
我正在开发 Merin Stack,用户可以在其中对程序发表评论,并且我还使用 Google-react-Recaptcha 来防止垃圾邮件。
一切都运行良好,除非用户忘记声明他们不是机器人(检查 Recaptcha 框)并且发布请求不成功。发生的情况是用户键入的输入被清除,并且似乎页面正在刷新失败的发布请求。
如何在失败的发布请求中使用户的输入无法从字段中清除?
这是我的onSubmit
功能
const [error, setError] = useState("");
const [token, setToken] = useState("");
const reCaptcha = useRef();
const onSubmit = useCallback((e) => {
if (!token) {
alert("Yoou must verify the captcha");
setError("Yoou must verify the captcha");
}
setError("");
e.preventDefault();
setName("");
setDescription("");
axios
.post(
"http://localhost:9000/programs/" +
props.match.params.id +
"/programcomment",
{ name: name, description: eventDescription, token }
)
.then(function (response) {
onPageLoad();
alert("Submitted Succefully");
})
.catch(function (err) {
setError(err);
console.log(err);
})
.finally(() => {
reCaptcha.current.reset();
setToken("");
});
});
和我的表单输入
<div className="container">
<div className="row " />
<div className="col-sm-2"></div>
<div className="col-sm-10"></div>
<div className="row">
<div className="col-sm-2" />
<div className="col-sm-10">
<form className="form" onSubmit={onSubmit}>
<div className="form-group">
<label htmlFor="name">Name:</label>
<input
type="text"
className="form-control"
id="name"
value={name}
required
onChange={handleChange("name")}
/>
<br />
<label htmlFor="comment">Comment:</label>
<textarea
className="form-control"
rows={5}
id="comment"
required
defaultValue={""}
value={eventDescription}
onChange={handleChange("description")}
/>
<br />
</div>
<ReCAPTCHA
ref={reCaptcha}
sitekey="6LecT-sZgfgrrtrtrtrtqQuMSJnMbxrif0ArqJqk2"
onChange={(token) => setToken(token)}
onExpired={(e) => setToken("")}
/>
<button
type="submit"
id="myBtn"
class="btn btn-success"
// onClick={handleSubscribe}
>
Submit
</button>
</form>
<p id="warning" />
</div>
</div>
解决方案
添加e.preventDefault();
到您的onSubmit
回调并包装到else
检查令牌后调用的块代码:
const onSubmit = useCallback((e) => {
e.preventDefault();
if (!token) {
alert("Yoou must verify the captcha");
setError("Yoou must verify the captcha");
} else {
setError("");
e.preventDefault();
setName("");
setDescription("");
axios
.post(
"http://localhost:9000/programs/" +
props.match.params.id +
"/programcomment",
{ name: name, description: eventDescription, token }
)
.then(function (response) {
onPageLoad();
alert("Submitted Succefully");
})
.catch(function (err) {
setError(err);
console.log(err);
})
.finally(() => {
reCaptcha.current.reset();
setToken("");
});
}
});
推荐阅读
- image - 保存 jsignature 图像不再透明
- javascript - 正则表达式:用嵌套元素替换字符串
- ruby-on-rails - 如何将此 curl 命令转换为 Ruby rest-client put 请求?
- android - 使用 clang 和 Manifest.xml 构建 C++ Android 应用程序
- reactjs - 带有打字稿的Hoc(高阶组件)在本机反应中
- flutter - Flutter 测试应用程序找不到 pubspec.yaml
- python - 什么时候应该使用 tf.train.BytesList、tf.train.FloatList 和 tf.train.Int64List 将数据存储在 tf.train.Feature 中?
- excel - 在新的 Excel 实例中打开 Excel OLEObject
- html - iframe div 需要额外的间距
- python - SMTPSenderRefused at /password-reset/ 错误