有人设法找到一个好的方式,如何通过编程导航到一个相对的链接,与反应路由器?
我已经将反应路由器相对链接用于声明性链接,但我找不到一种以编程方式实现该功能的好方法。
我知道这可以用解析路径名和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`发布于 2016-07-28 11:24:37
如果您使用的是browserHistory,这很简单
browserHistory.push('/yourRelativePath');为此,请确保您有最新的反应性路由器和
import { browserHistory } from 'react-router';https://stackoverflow.com/questions/38634697
复制相似问题