首页 > 解决方案 > 在输入一些数据后离开页面前提醒用户(特别是在 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" },
      });
};

这将在我提交表单时起作用,但我想在用户单击后退按钮或任何导航链接时进行提示。

标签: reactjsreact-hook-form

解决方案


在 reactjs 的功能组件中,我使用了下面的东西。这对我有用。在我离开当前页面的情况下,我想删除一些商店数据。在那种情况下,我使用了下面的东西。

useEffect(() => {
  return () => {
       // you can add your functionality here  
   };
 }, []);

推荐阅读