reactjs - 在输入一些数据后离开页面前提醒用户(特别是在 ReactJS 中)
问题描述
我正在创建一个页面,用户需要在其中输入详细信息才能将产品添加到产品列表中。如果用户在表单中输入一些数据后不小心移出该页面,则在移出前应强制用户确认。但我正在努力满足这个要求。我正在使用将react-hook-form
数据存储在 JSON 服务器中。
我正在使用 state leave
,如果它是真的,那么在搬出之前提醒用户什么都没有。
const [leave, setLeave] = useState(false);
现在,我不知道在哪里以及如何使用此状态在离开前显示警报框。这是我将呈现的表单。
render (
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Row>
<Form.Group as={Col} className="mr-5">
<Form.Label column>Product Name</Form.Label>
<Form.Control
name="productName"
placeholder="Enter product Name"
required
ref={register}
/>
</Form.Group>
</Form.Row>
<Button variant="success" type="submit" className="text-white mt-5">
Add New Product
</Button>
</Form>
<Prompt when={Leave} message="Are you sure you want to leave ?" /> {/*Here I have promted*/}
);
为简单起见,我只给出了一个输入字段。现在 onSubmit 的函数定义如下。
const onSubmit = (formData) => {
setLeave(true); //here I am setting this true
axios.post("http://localhost:4000/products", formData);
navigation.push({
pathname: "/productList",
state: { added: "pass" },
});
};
这将在我提交表单时起作用,但我想在用户单击后退按钮或任何导航链接时进行提示。
解决方案
在 reactjs 的功能组件中,我使用了下面的东西。这对我有用。在我离开当前页面的情况下,我想删除一些商店数据。在那种情况下,我使用了下面的东西。
useEffect(() => {
return () => {
// you can add your functionality here
};
}, []);
推荐阅读
- html - 页面没有在 html 和 css 中一直滚动到底部
- java - 从 URL 读取:错误
- java - 如何使用 PDFBox 将 PDF 文件的一部分呈现为图像?
- mysql - 不知道如何 GROUP_BY 我的数据
- tsql - 插入和选择
- python - BS4 返回 HTML 缺失的元素
- google-app-engine - 您可以在基于 Cloud Pub/Sub 队列的 Google App Engine 中触发自动缩放吗?
- java - 如果我有一个清单
> 什么是删除任何其他集合的子集的任何集合的快速方法? - python - 如何返回包含字符串的行,而不是匹配整个字符串?
- javascript - React Native“无法加载[端点]:预检响应无效(重定向)”