• 技术文章 >web前端 >前端问答

    react怎么实现路由跳转前确认

    藏色散人藏色散人2023-01-19 11:18:09原创64

    react实现路由跳转前确认功能的方法:1、通过“import { Modal } from 'antd';”方法引入“antd”;2、使用Antd的“Modal.confirm”实现弹框;3、设置Form表单内容即可。

    本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

    react怎么实现路由跳转前确认?

    react-router 跳转前确认Prompt使用

    需求

    页面切换的时候,会遇到这样的需求:切换时需要判断内容区域编辑后是否保存了, 若没保存,则弹出提示框,提示保存。

    76e3f238f1706dafbeef6b076cc6f23.jpg

    官网示例

    react router中的Prompt可以实现这样的功能。

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

    实现

    我们项目的技术栈umi+antd+react

    弹框用的Antd的 Modal.confirm

    import React, { useEffect, useState } from 'react';
    import { Modal } from 'antd';
    import { useBoolean } from '@umijs/hooks';
    // umi里封装了该组件
    // 或者 import { Prompt } from "react-router-dom";
    import { useParams, history, Prompt } from 'umi';
    import {
      ExclamationCircleOutlined
    } from '@ant-design/icons';
    import {  isEqual } from '@/utils/utils';
    import { FormInstance } from 'antd/lib/form';
    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 !== '0') {
              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: '暂未保存您所做的更改,是否保存?',
                okText: '保存',
                cancelText: '不保存',
                onOk() {
                  formInstance?.submit();
                  nextStep(location.pathname);
                },
                onCancel() {
                  nextStep(location.pathname);
                }
              });
              return false;
            }}
          />
        </div>
      );
    }

    推荐学习:《react视频教程

    以上就是react怎么实现路由跳转前确认的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:React
    上一篇:react怎么引入外部方法 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • react怎么改字体• react element什么意思• react build 路径不对怎么办• react怎么实现三级菜单• react怎么引入外部方法
    1/1

    PHP中文网