思路:利用react-route-dom的history.block进行锁定
注意:6版本的react-route-dom history.block的返回值是解锁函数,return无效
效果:项目内的路由操作都可以执行自己的组件,游览器url操作会执行原生对话框
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);