【发布时间】: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