天天看點

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);      

歡迎關注前端早茶,與廣東靓仔攜手共同進階

​​

​​

繼續閱讀