React-router:阻止导航到目标路由

问题描述 投票:7回答:1

我正在使用带有历史记录useQueries(createHashHistory)() react-router,并且我想要根据路由的配置阻止导航到多个路由。
所以路由配置如下:

<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>

所以我们假设我在#/view-2并调用像history.push({pathname: '/view-1'});这样的动作history.push({pathname: '/view-1'}); 。 但是一旦路由view-1有一个标志canNavigate={false} - 我想阻止导航到它并显示消息而不更改散列和任何其他副作用 (比如调用onLeave view-2 onLeave钩子)。

我在考虑听history

history.listenBefore((location, callback) => {
    //e.g. callback(false) to prevent navigation
})

但我无法获取路由实例来检查canNavigate标志。
后来我发现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);
        }
    });
})

但问题是history.matchview-2内部调用onLeave hook(例如,即使用户停留在view-2视图上,也可以清除状态)。

问题 :在历史/路由器中是否可以阻止从view-2导航而根本没有任何更改并根据目标路由配置做出此决定?

javascript reactjs react-router browser-history
1个回答
1
投票

一旦调用history.push,React就无法阻止导航。

您应该使用自定义的服务器封装历史服务,该服务将检查是否可以导航,如果是,则调用history.push。 否则阻止导航并保持状态。

© www.soinside.com 2019 - 2024. All rights reserved.