Fork me on GitHub

react 利用history.blcok实现路由跳转拦截

欢迎关注前端早茶,与广东靓仔携手共同进阶
前端早茶专注前端,一起结伴同行,紧跟业界发展步伐~
 

一、前言

“history 对象”指的是history软件包,它是 React Router 仅有的两个主要依赖项之一(除了 React 本身),它提供了几种不同的实现来管理各种环境中 JavaScript 的会话历史。
 

二、功能介绍

思路:利用react-route-dom的history.block进行锁定
注意:6版本的react-route-dom history.block的返回值是解锁函数,return无效
效果:项目内的路由操作都可以执行自己的组件,游览器url操作会执行原生对话框
 
包说明
 
package description
 react-router  路由核心功能
 react-router-dom  基于react-router提供在浏览器运行环境下功能
 react-router-native  for React Native
 react-router-config  static route congif helpers
 
history 对象通常包含以下属性:

length - (number): history 中的记录数量
action - (string): 当前的操作(PUSH, POP, REPLACE)
location - (object): 当前的 location 对象
push - (path, [state]): 向 history 栈推一条记录
replace - (path, [state]): 将 history 栈顶部的记录替换
go - (n): 在 history 栈中移动 n 步
goBack - (): 与 go(-1)相同
goFoward - (): 与 go(1)相同
block - (prompt): 阻止导航

 

三、使用

import React, { useEffect, useState } from "react";
import { Routes, Route } from "react-router-dom";
import { confirm } from 'xx-design';

import ProjectViewer from './page/car/project';
// ...若干引入...

const RouteViewer = (props) => {
  const { history } = props;
  const [lock, changeLock] = useState(false);
  const [location, changeLocation] = useState(history.location);

  useEffect(() => {
    const unListen = history.listen(({ location: newLocation }) => {
      if (newLocation) {
        changeLocation(newLocation);
      }
    });
    return () => {
      unListen();
    }
  }, [])
  useEffect(() => {
    let unBlock;
    if (lock) {
      // 上锁
      unBlock = history.block(({ location: nextLocation }) => {
        // 自己的弹窗组件
        confirm({
          content: '退出后,未上传的视频将不再继续上传!</br>确定退出吗?',
          onOk: () => {
            changeLock(false);
            unBlock();
             // 解锁后继续跳转
            history.push(nextLocation.pathname);
          },
        });
      });
    } else {
      unBlock && unBlock(); // 解锁
    }
  }, [lock])
  return (
    <Routes location={location}>
      <Route path="/" group="car" element={<ProjectViewer history={history} />} />
      <Route path="/car" group="car" element={<ProjectViewer history={history} />} />
      ...若干路由...
      <Route path="devicesHistory/:name" group="console" element={<DevicesHistory changeLock={changeLock} history={props.history} />} />
      <Route path="*" element={<main style={{ padding: '1rem' }}><p>404</p></main>} />
    </Routes>
  );
}

export default RouteViewer;

 

import React, { useState, useEffect } from "react";
import { connect } from "react-redux";

const Viewer = (props) => {
  const handlerDis = () => {
// 点击上锁
     props.changeLock(true);
  }
  useEffect(() => {
   return () => {
// 卸载的时候解锁
      changeLock(false);
    }
  }, []);

  return (
    <div><button onClick={handlerDis}>点击上锁</button></div>
  );
};

export default  (Viewer);
 
欢迎关注前端早茶,与广东靓仔携手共同进阶
前端早茶专注前端,一起结伴同行,紧跟业界发展步伐~
posted @ 2022-11-02 10:20  广东靓仔-啊锋  阅读(904)  评论(0编辑  收藏  举报