How to implement confirmation before routing jump in react

藏色散人
Release: 2023-01-19 11:18:09
Original
1591 people have browsed it

React method to implement the confirmation function before routing jump: 1. Introduce "antd" through the "import { Modal } from 'antd';" method; 2. Use Antd's "Modal.confirm" to implement the pop-up box ; 3. Set the form content.

How to implement confirmation before routing jump in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to confirm before routing jump in react?

react-router Confirm Prompt before jumping using

Requirements

When switching pages, you will encounter such requirements: Switch It is necessary to determine whether the content area has been saved after editing. If not, a prompt box will pop up to prompt for saving.

How to implement confirmation before routing jump in react

Official website example

Prompt in react router can achieve such a function.

Prompt示例:https://reactrouter.com/web/example/preventing-transitions
Prompt文档:https://reactrouter.com/core/api/Prompt
Copy after login
/** when:是否启用 */
/** message:string | func */
// 示例1
<Prompt
  when={formIsHalfFilledOut}
  message="Are you sure you want to leave?"
/>
// 示例2
<Prompt
  message={(location, action) => {
    if (action === &#39;POP&#39;) {
      console.log("Backing up...")
    }
    return location.pathname.startsWith("/app")
      ? true
      : `Are you sure you want to go to ${location.pathname}?`
  }}
/>
Copy after login

Implementation

The technology stack of our project umi antd react

Modal.confirm of Antd used in the pop-up box

import React, { useEffect, useState } from &#39;react&#39;;
import { Modal } from &#39;antd&#39;;
import { useBoolean } from &#39;@umijs/hooks&#39;;
// umi里封装了该组件
// 或者 import { Prompt } from "react-router-dom";
import { useParams, history, Prompt } from &#39;umi&#39;;
import {
  ExclamationCircleOutlined
} from &#39;@ant-design/icons&#39;;
import {  isEqual } from &#39;@/utils/utils&#39;;
import { FormInstance } from &#39;antd/lib/form&#39;;
export default function BaseInfo() {
  const { id } = useParams<{ id: string }>(); 
  // 保留原始数据
  const [orginData, setOrigin] = useState({});
  // 修改后的数据
  const [modifyData, setModify] = useState({});
  // 是否启用Prompt
  const { state, setTrue, setFalse } = useBoolean(false);
  // 还原信息 useLoading是自己封装的hooks
  const [isFetching, fetchInfo] = useLoading(getServiceGroupDetail);
  useEffect(() => {
    (async () => {
      try {
        if (id !== &#39;0&#39;) {
          const info = await fetchInfo(id);
          setOrigin({
            ...info 
          });
          setModify({
            ...info 
          });          
        }
      } catch (e) {
        console.error(e);
      }
    })();
  }, [id]);
  useEffect(() => {
    if (isEqual(orginData, modifyData)) {
      setFalse();
    } else {
      setTrue();
    }
  }, [orginData, modifyData]);
  const nextStep = (pathname?: string) => {
    setFalse();
    pathname &&
      setTimeout(() => {
        history.push(pathname);
      });
  };
  return (
      {/* 这里原来放的Form表单内容 */}
      {routerWillLeave(state, form, nextStep)}
  );
}
function routerWillLeave(
  isPrompt: boolean | undefined,
  formInstance: FormInstance, // 保存,我这个页面是Form表单
  nextStep: (pathname?: string) => void
) {
  return (
    <div>
      <Prompt
        when={isPrompt}
        message={(location) => {
          if (!isPrompt) {
            return true;
          }
          Modal.confirm({
            icon: <ExclamationCircleOutlined />,
            content: &#39;暂未保存您所做的更改,是否保存?&#39;,
            okText: &#39;保存&#39;,
            cancelText: &#39;不保存&#39;,
            onOk() {
              formInstance?.submit();
              nextStep(location.pathname);
            },
            onCancel() {
              nextStep(location.pathname);
            }
          });
          return false;
        }}
      />
    </div>
  );
}
Copy after login

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement confirmation before routing jump in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template