【问题标题】:How to use history in a child of BrowserRouter?如何在 BrowserRouter 的子节点中使用历史记录?
【发布时间】:2019-05-03 13:23:07
【问题描述】:

我收到此错误:

'Invariant failed: Browser history needs a DOM'

我已经尝试了大部分通过谷歌搜索找到的东西,但似乎没有任何效果。

目前我的简化设置是这样的

<BrowserRouter forceRefresh={!supportsHistory}>
    <App />
</BrowserRouter>

App 是这样的:

import history from './history';

<Router history={history}> // I have to remove Router for it to work at all
    <Switch>
        <Route1 irrelevant/>
        <Route2 irrelevant/>
    </Switch>
</Router>

history.js:

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

路线2:

import history from './history';
import { withRouter } from 'react-router-dom';

<button onClick={() => history.goBack()}>

export default withRouter(Route2);

我使用历史记录的唯一原因是我的第二条路线中的 goBack 功能。所以如果有另一种方法我很好奇,或者是否有办法让历史工作。

【问题讨论】:

  • 您是否将一个路由器包裹在另一个路由器中?我认为这可能会导致冲突(未测试)
  • 是的,这似乎确实引起了问题。在 App 中删除 Router 可使路由正常工作,但我完全丢失了历史记录:D 而且我无法将 BrowserRouter 更改为 Router,因为 forceRefresh 的额外字段
  • 我还用评论编辑了主要问题,感谢您的关注:D

标签: react-router browser-history react-router-dom history.js


【解决方案1】:

要访问由您的路由器控制的历史实例,您应该使用withRouter,它允许您访问路由器属性:

import { withRouter } from "react-router";
import React from "react";

  render() {
    const { history } = this.props;

    return <button onClick={() => history.goBack()}>;
  }
}

【讨论】:

  • 啊,对不起,我忘了补充。我已经将 withRouter 添加到了导出中。我将编辑初始帖子
猜你喜欢
  • 2022-10-15
  • 2019-12-26
  • 2021-09-02
  • 1970-01-01
  • 2018-12-31
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多