在 goBack() 反应路由器 v4 之前检查历史以前的位置 [英] Check history previous location before goBack() react router v4
问题描述
我的目标是启用返回"按钮,但前提是用户返回的路线/路径属于某个类别.
My goal is to enable a "Go Back" button, but only if the route/path the user would go back to is in a certain category.
更准确地说,我有两种路由:/
和 /graph/
.当用户在图表之间导航时,他们应该能够返回到上一个图表,但不能返回到 /...
路线.这就是为什么我不能简单地运行history.goBack()
,我需要先检查位置.
More precisely I have two kinds of Routes : /<someContent>
and /graph/<graphId>
. When the user navigates between graphs they should be able to go back to the previous graph but not to a /...
route. This is why I can't simply run history.goBack()
, I need to check the location first.
const history = createHashHistory();
const router = (
<ConnectedRouter history={history}>
<Switch>
<Route exact path='/' component={Home}></Route>
<Route exact path='/extension' component={Home}></Route>
<Route exact path='/settings' component={Home}></Route>
<Route exact path='/about' component={Home}></Route>
<Route exact path='/search' component={Home}></Route>
<Route exact path='/contact' component={Home}></Route>
<Route path='/graph/:entityId' component={Graph}></Route>
</Switch>
</ConnectedRouter>
);
我想在 Graph
组件中实现类似的东西:
I'd like to implement something like this in the Graph
component:
if (this.props.history.previousLocation().indexOf('graph') > -1){
this.props.history.goBack();
} else {
this.disableReturnButton();
}
这个问题也适用于 goForward()
因为如果不适用,我想禁用前进"按钮.用户也用 this.props.history.push(newLocation)
This question also applies to goForward()
as I'd like to disable the "forward" button if not applicable. Also the user moves around with this.props.history.push(newLocation)
显然,当用户四处走动时,我想避免使用诸如登录 localStorage
或 redux store
之类的小技巧,这感觉不太自然,我知道如何去做.
Obviously I'd like to avoid using side-tricks like logging in localStorage
or a redux store
as the user moves around, it feels less natural and I know how to do it.
推荐答案
在通过 Link
组件或即使通过 history.push
导航时,您可以传递当前位置到另一个 Route
组件
While navigating though the Link
component or even though history.push
, you could pass the current location to another Route
component
喜欢
<Link to={{pathname: '/graph/1', state: { from: this.props.location.pathname }}} />
或
history.push({
pathname: '/graph/1',
state: {
from: this.props.location.pathname
}
})
然后你可以在你的组件中获取这个位置,比如 this.props.location.state &&this.props.location.state.from
然后决定是否要goBack
and then you could just get this location in your Component like this.props.location.state && this.props.location.state.from
and then decide whether you wan't to goBack
or not
这篇关于在 goBack() 反应路由器 v4 之前检查历史以前的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!