[英]React-router: prevent navigation to target route
I'm using react-router with history useQueries(createHashHistory)()
and I have several routes that I want to prevent navigation to based on route's configuration. 我正在使用带有历史记录
useQueries(createHashHistory)()
react-router,并且我想要根据路由的配置阻止导航到多个路由。
So routes config is like: 所以路由配置如下:
<Route path="/" name={RouteNames.APP} component={AppContainer}>
<Route path="view-1"
onEnter={ view1onEnter }
onLeave={ view1onLeave }
component={ View1 }
canNavigate={ false }
/>
<Route path="view-2"
onEnter={ view2onEnter }
onLeave={ view2onLeave }
component={ View2 }
canNavigate={ true }
/>
...
</Route>
So let's assume I'm on #/view-2
and call an action like history.push({pathname: '/view-1'});
所以我们假设我在
#/view-2
并调用像history.push({pathname: '/view-1'});
这样的动作history.push({pathname: '/view-1'});
. 。 But as soon as route
view-1
has a flag canNavigate={false}
- I want to prevent navigation to it and show a message without changing a hash and any other side effects (like calling onLeave
hook of view-2
). 但是一旦路由
view-1
有一个标志canNavigate={false}
- 我想阻止导航到它并显示消息而不更改散列和任何其他副作用 (比如调用onLeave
view-2
onLeave
钩子)。
I was thinking about listening to history
: 我在考虑听
history
:
history.listenBefore((location, callback) => {
//e.g. callback(false) to prevent navigation
})
but I can't get the route instance to check canNavigate
flag. 但我无法获取路由实例来检查
canNavigate
标志。
Later I've found out that history
has a method match
which actually gets next router state based on the given location
: 后来我发现
history
有一个方法match
,实际上根据给定的location
得到下一个路由器状态:
history.listenBefore((location, callback) => {
history.match(location, (error, redirectLocation, nextState) => {
const route = _.last(nextState.routes);
if (route.canNavigate) {
callback();
} else {
callback(false);
}
});
})
but the problem is that history.match
calls onLeave
hook for view-2
inside (which may, for example, clear state even though the user stays on the view-2
view). 但问题是
history.match
为view-2
内部调用onLeave
hook(例如,即使用户停留在view-2
视图上,也可以清除状态)。
The question : is it possible to prevent navigation from view-2
without any changes at all in history/router and making this decision based on target route configuration? 问题 :在历史/路由器中是否可以阻止从
view-2
导航而根本没有任何更改并根据目标路由配置做出此决定?
React cannot prevent the navigation once you've called history.push. 一旦调用history.push,React就无法阻止导航。
You should encapsulate the history service with a custom one that will check whether it is possible to navigate and if it is then call history.push. 您应该使用自定义的服务器封装历史服务,该服务将检查是否可以导航,如果是,则调用history.push。 otherwise prevent the navigation and keep the state.
否则阻止导航并保持状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.