如何修复未捕获的DOMException:无法在“历史记录”上执行“ pushState”

时间:2019-04-27 14:38:23

标签: reactjs router webpack-4

我有一个小应用程序,可以在开发模式下使用webpack-dev-server正常工作,但是当我使用生产模式生成的dist文件夹中的捆绑文件时,在浏览器中看到的只是这个错误:

Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'file:///C:/' cannot be created in a document with origin 'null' and URL 'file:///C:/Users/cristi/work/react_test_ground/dist/index.html'.

如何解决这个pushState问题?

由于webpack抛出此错误,最初我尝试使用React.lazy和Suspense拆分代码:

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  2c7b7b6becb423b8f2ae.bundle.js (413 KiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  main (413 KiB)
      2c7b7b6becb423b8f2ae.bundle.js


WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of
your application.

但是问题仍然存在。

您可以在此处查看代码和完整的存储库:https://github.com/cristiAndreiTarasi/temporary

App.js

import React, { Fragment, Suspense, lazy } from 'react';
import { BrowserRouter, Route, Link, Switch } from 'react-router-dom';

const Home = lazy(() => import('./Home'));
const Blog = lazy(() => import('./Blog'));
const Contact = lazy(() => import('./Contact'));

export default () => (
    <BrowserRouter>
        <div>
            <ul>
                <li><Link to='/'>Home</Link></li>
                <li><Link to='/blog'>Blog</Link></li>
                <li><Link to='/contact'>Contact</Link></li>
            </ul>

            <Suspense fallback={<p>Loading...</p>}>
                <Switch>
                    <Route exact path='/' component={Home} />
                    <Route path='/blog' component={Blog} />
                    <Route path='/contact' component={Contact} />
                </Switch>
            </Suspense>
        </div>
    </BrowserRouter>   
);

其他组件的格式如下:

import React from 'react';

export default () => (
    <div>
        <h1>Hello from the Blog</h1>
        <img src='../images/landscape-art_large.jpg' />
    </div>
);

我想从生产模式所产生的捆绑文件中获得与开发模式相同的结果。

3 个答案:

答案 0 :(得分:1)

您应该通过Web服务器打开文件。因为您无法在file:// api上更改位置历史记录。

答案 1 :(得分:0)

您可以使用 HashRouter MemoryRouter 代替BrowserRouter。

只需替换此行:

import { BrowserRouter, Route, Link, Switch } from 'react-router-dom';

具有:

import { HashRouter, Route, Link, Switch } from 'react-router-dom';

或:

import { MemoryRouter, Route, Link, Switch } from 'react-router-dom';

然后在浏览器中打开您构建的index.html文件,一切应该像使用localhost / dev服务器一样工作。

答案 2 :(得分:0)

我有此错误(尽管在我的react应用程序中),因为我提供了而不是searchParams url ,而是将整个URL放入了history.pushState http://localhost:9090/admin/model-type?PageNumber=2 但搜索查询应为?PageNumber=2

history.pushState(
        {[paramKey]: paramValue},
        'page title',
        url
      )