【问题标题】:Is there a way to use history with HashRouter, with react-router v4?有没有办法通过 HashRouter 和 react-router v4 使用历史记录?
【发布时间】:2020-12-16 02:35:03
【问题描述】:

我需要在 React 组件之外重定向用户,这通常使用 history 和 react-router 来完成。

// history.js
const history = createBrowserHistory();
export default history;

// App, setting up router
import { HashRouter as Router } from 'react-router-dom';
import history from './history';
...
<HashRouter history={history}>...</HashRouter> // problem

// Non-component file
import history from './history';
history.push('/target');

由于HashRouter 不采用历史道具,而是在内部处理历史记录,并且开发人员被指示使用withRouter 以将history 暴露给组件,因此如何在外部进行重定向并不明显一个组件。

我正在使用HashRouter 并且我需要在组件外部使用history(这意味着我不能使用withRouter)。

我怎样才能做到这一点?

【问题讨论】:

    标签: react-router react-router-dom react-router-v4


    【解决方案1】:

    是的,有一种方法可以同时使用history 和基于哈希的路由器。

    创建历史实例时,使用createHashHistory 而不是createBrowserHistory

    // myCreatedHistory.js
    import { createHashHistory } from 'history';
    export default createHashHistory();
    

    不要使用HashRouter,而是使用低级别的Router,并将history 属性传递给它,就像这样。

    // App
    import { Router } from 'react-router-dom';
    import history from '../myCreatedHistory';
    ...
    <Router basename="/" history={history}>...</Router>
    

    然后您可以从任何地方(比如中间件)导入history

    // Middleware, or anywhere
    import history from '../myCreatedHistory';
    history.push('/target');
    

    【讨论】:

    • 它只路由到所需的 url 但 ui 中没有更新,它显示空白页
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2017-10-22
    • 2017-12-08
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多