与 react-router 的编程相对链接

Programmatic relative links with react-router

本文关键字:相对 链接 编程 react-router      更新时间:2023-09-26

有人设法找到一种好方法,如何以编程方式导航到带有 react-router 的相对链接?

我已经将反应路由器相对链接用于声明性链接,但我找不到以编程方式执行此操作的好方法。

我知道可以使用解析路径名和router.push(…)手动完成,但这需要访问location,这仅在路由处理程序组件上可用。我的组件在树的深处,因此我想避免所有接线回到顶部。

window.location.pathname获取位置然后通过withRouter使用router.push的正确方法吗?

目前我将其用作实用程序函数:

import resolvePathname from 'resolve-pathname';
function getPathnameFromRelativeLocation(relativeLocation) {
  let {pathname} = window.location;
  let basePath = pathname.endsWith('/') ? pathname : pathname + '/';
  return resolvePathname(relativeLocation, basePath);
}

在 React 组件的事件处理程序中:

// Current path is `/books/123`
let path = getPathnameFromRelativeLocation('write-review');
this.props.router.push(path);
// Current path is `/books/123/write-review`

react-router 3.0 现在提供了上下文location,因此现在可以轻松地从那里获取它。

https://github.com/ReactTraining/react-router/issues/3325

如果您使用的是浏览器历史记录 简直就是

browserHistory.push('/yourRelativePath');

为此,请确保您拥有最新的反应路由器和

 import { browserHistory } from 'react-router';