【发布时间】:2018-05-04 17:01:36
【问题描述】:
我的目标是启用“返回”按钮,但前提是用户返回的路线/路径属于某个类别。
更准确地说,我有两种路线:/<someContent> 和 /graph/<graphId>。当用户在图表之间导航时,他们应该能够返回上一个图表,但不能返回/... 路线。这就是为什么我不能简单地运行history.goBack(),我需要先检查位置。
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 组件中实现类似的东西:
if (this.props.history.previousLocation().indexOf('graph') > -1){
this.props.history.goBack();
} else {
this.disableReturnButton();
}
这个问题也适用于goForward(),因为如果不适用,我想禁用“前进”按钮。用户也可以使用this.props.history.push(newLocation)移动
显然,当用户四处走动时,我想避免使用诸如登录localStorage 或redux store 之类的副作用,这感觉不太自然,我知道该怎么做。
【问题讨论】:
-
如果您的历史记录是由
window.history支持的,您就看不到.back()或.forward()背后的内容????我不确定哈希历史是否以相同的方式实现,但我很确定它具有相同的 API,所以没有运气。我认为在内存中保留历史的影子副本(您的 reduxstore想法)是最实用的方式。
标签: javascript reactjs ecmascript-6 react-router