diff --git a/packages/preset-umi/src/features/tmpFiles/tmpFiles.ts b/packages/preset-umi/src/features/tmpFiles/tmpFiles.ts index 305727e5458c..bbecd1153ce3 100644 --- a/packages/preset-umi/src/features/tmpFiles/tmpFiles.ts +++ b/packages/preset-umi/src/features/tmpFiles/tmpFiles.ts @@ -582,6 +582,14 @@ if (process.env.NODE_ENV === 'development') { reactRouter5Compat, }, }); + api.writeTmpFile({ + noPluginDir: true, + path: 'core/location.ts', + tplPath: join(TEMPLATES_DIR, 'location.tpl'), + context: { + historyWithQuery, + }, + }); api.writeTmpFile({ noPluginDir: true, path: 'core/historyIntelli.ts', @@ -670,6 +678,13 @@ if (process.env.NODE_ENV === 'development') { exportMembers, path: '@@/core/history.ts', }); + // @@/core/location.ts + exports.push(`export { useLocation } from './core/location';`); + checkMembers({ + members: ['useLocation'], + exportMembers, + path: '@@/core/location.ts', + }); // @@/core/terminal.ts if (api.service.config.terminal !== false) { exports.push(`export { terminal } from './core/terminal';`); diff --git a/packages/preset-umi/templates/location.tpl b/packages/preset-umi/templates/location.tpl new file mode 100644 index 000000000000..8f49311ce412 --- /dev/null +++ b/packages/preset-umi/templates/location.tpl @@ -0,0 +1,20 @@ +// location.tpl +import { useState, useEffect } from 'react'; +import { useLocation as defaultUseLocation } from 'react-router-dom'; +import { history } from './history'; + +function useLocationCompat() { + const [location, setLocation] = useState(history.location); + + useEffect(() => { + const unlisten = history.listen((update) => { + setLocation(update.location); + }); + + return unlisten; + }, []); + + return location; +} + +export const useLocation = {{#historyWithQuery}}useLocationCompat{{/historyWithQuery}}{{^historyWithQuery}}defaultUseLocation{{/historyWithQuery}}; diff --git a/packages/renderer-react/src/index.ts b/packages/renderer-react/src/index.ts index 7ab2961d3499..9f12cd49eb8a 100644 --- a/packages/renderer-react/src/index.ts +++ b/packages/renderer-react/src/index.ts @@ -14,7 +14,6 @@ export { NavLink, Outlet, resolvePath, - useLocation, useMatch, useNavigate, useOutlet,