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

思路:利用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: '退出后,未上传的视频将不再继续上传!
确定退出吗?', onOk: () => { changeLock(false); unBlock(); // 解锁后继续跳转 history.push(nextLocation.pathname); }, }); }); } else { unBlock && unBlock(); // 解锁 } }, [lock]) return ( } /> } /> ...若干路由... } />

404

} />
); } 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 (
    
); }; export default (Viewer);

你可能感兴趣的:(利用history.blcok 实现路由跳转拦截)