【问题标题】:Use react history object to change last browser's URL使用反应历史对象更改最后一个浏览器的 URL
【发布时间】:2018-11-01 06:51:54
【问题描述】:

我目前正在尝试从以下位置使用 history.push() 对象: https://github.com/ReactTraining/history

点击浏览器的后退按钮时,我无法更改浏览器的最后一个 URL。

当我使用 history.push(...) 时,当前浏览器的 URL 会发生变化;有办法避免这种情况吗?或者只是使用窗口对象我可以做到这一点?

我的应用程序不是单页应用程序;代码:

    import createHistory from 'history/createBrowserHistory';
    const history = createHistory();
    const testUrl = 'http://test.com'

    history.push(testUrl);
    window.addEventListener('popstate', (event) => {
        history.go(testUrl);
    });

【问题讨论】:

    标签: reactjs browser react-router


    【解决方案1】:

    您可以使用pushStatereplace。 pushState 添加一个新条目,而 replace 修改当前条目。

    @见https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history

    正如我从您的模块history/createBrowserHistory 中看到的,您正在使用this 模块,它应该与本机实现完全兼容。

    【讨论】:

    • 是的,pushState 将是一个解决方案。但我希望使用 react 对象来做到这一点。感谢您的回复 x)
    • 反应对象?你在那里不使用任何反应对象。您从这里使用完全兼容的层,这与反应没有任何关系。 npmjs.com/package/history
    • 你是对的。我仍然不能使用推送和替换,使用时都会更改 URL。
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 2016-01-27
    • 2019-12-15
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多