【问题标题】:How can I get the previous url in javascript?如何在 javascript 中获取以前的 url?
【发布时间】:2021-11-08 00:57:20
【问题描述】:

我需要在 nextjs 项目中获取上一个 url。我找到了this,但它没有帮助,因为它总是使用这种方法(document.referrer)打印我的基本网址(http://localhost:3000/)。我还尝试根据官方developer mozilla doc 将状态推送到 window.history 中。

在最后一种情况下,我单击一个链接,它会将我重定向到另一个页面。在这个页面上,我需要知道我来自哪里。我试过了:

//pathname is a string containing the actual pathname
history.pushState({prevPath: pathname},pathname)

如果我在新页面中打印 history,那么我在 state 字段中看不到任何 prevState

【问题讨论】:

  • history.pushState({foo:bar},'title',pathname) ?
  • 最后一个参数是可选的。我也尝试过这种方式,但没有任何改变。我总是得到这个: state: { "url": "/search?keyword=tag1", "as": "/search?keyword=tag1", "options": { "scroll": true }, "__N": true, "idx": 23 } state 是历史状态
  • AND with history.replaceState(stateObj, "page 3", "bar2.html"); ?没有踪迹?
  • 这是否回答了您的问题:How to get history and match in this.props in nextjs??查看最佳答案中的 useRouteUrlHistory 钩子实现。

标签: javascript reactjs next.js


【解决方案1】:

您可以简单地创建一个状态,它是一个具有两个属性的对象:previousUrlcurrentUrl,如下所示:

const urlReducer = (state={previousUrl: null, currentURL: null},action) => {
    switch(action.type){
        case "SET_URLS":
            return {previousUrl: state.currentUrl, currentUrl: window.location.href}
        default:
            return state;
    }
}

那么您需要做的就是在您访问的每个页面中发送一个操作,如下所示:

const dispatch = useDispatch();

useEffect(()=>{
    dispatch({type: "SET_URLS"});
},[]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2015-02-16
    • 2022-08-12
    • 2019-09-23
    • 2015-04-04
    • 2023-03-15
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多