gpt4 book ai didi

javascript - 在 goBack() react 路由器 v4 之前检查历史记录之前的位置

转载 作者:可可西里 更新时间:2023-11-01 02:08:48 26 4
gpt4 key购买 nike

我的目标是启用“返回”按钮,但前提是用户要返回的路线/路径属于特定类别。

更准确地说,我有两种路线:/<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当用户四处移动时,感觉不那么自然,我知道该怎么做。

最佳答案

在通过 Link 组件或什至通过 history.push 导航时,您可以将当前位置传递给另一个 Route 组件

喜欢

<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 然后决定是否要 返回 或不返回

关于javascript - 在 goBack() react 路由器 v4 之前检查历史记录之前的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47409586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com