UNPKG

react-router-block

Version:

基于react-router v6版本的路由守卫,让你能使用类似vue-router那样的路由守卫

84 lines (65 loc) 2.06 kB
import React, { memo, useEffect } from 'react'; import { useNavigate, useLocation, useRoutes } from 'react-router-dom'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var _excluded = ["pathname"]; var from = null; function RouterBlock(_ref) { var _ref$routes = _ref.routes, routes = _ref$routes === void 0 ? [] : _ref$routes, beforeEnter = _ref.beforeEnter, children = _ref.children; if (children === undefined && routes.length === 0) { throw new Error('children 和 routes必须要有一个'); } var navigate = useNavigate(); var _useLocation = useLocation(), path = _useLocation.pathname, rest = _objectWithoutPropertiesLoose(_useLocation, _excluded); var renderElement = useRoutes(routes); var next = function next(to) { if (to === undefined) return; if (typeof to === 'string') { to.startsWith('/') ? navigate(to) : navigate(path + "/" + to); } }; useEffect(function () { beforeEnter(_extends({}, rest, { path: path }), next, from); return function () { // 给from赋上一次的值 from = _extends({}, rest, { path: path }); }; }); return React.createElement("div", null, " ", children !== undefined ? children : renderElement); } var index = /*#__PURE__*/memo(RouterBlock); export default index; //# sourceMappingURL=react-router-block.esm.js.map