[英]How can I get the previous url in javascript?
I need to get the previous url in a nextjs project.我需要在 nextjs 项目中获取上一个 url。 I found this but it doesn't help because it always prints me the base url (
http://localhost:3000/
) with this method ( document.referrer
).我发现了这个,但它没有帮助,因为它总是使用这种方法(
document.referrer
)向我打印基本 URL( http://localhost:3000/
)。 I also tried to push a state into window.history based on official developer mozilla doc.我还尝试根据官方开发人员 mozilla文档将状态推送到 window.history 中。
In the last case I click on a link and it redirects me to another page.在最后一种情况下,我单击一个链接,它将我重定向到另一个页面。 On this page I need to know where I come from.
在这个页面上,我需要知道我来自哪里。 I tried:
我试过:
//pathname is a string containing the actual pathname
history.pushState({prevPath: pathname},pathname)
If I print history in the new page then I don't see any prevState in the state field.如果我在新页面中打印历史记录,那么我在 state 字段中看不到任何prevState 。
You can simply create a state which is an object that has two properties: previousUrl
and currentUrl
like this:您可以简单地创建一个状态,它是一个具有两个属性的对象:
previousUrl
和currentUrl
如下所示:
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;
}
}
Then all you need to do is dispatch an action in every page you visit like this:然后你需要做的就是在你访问的每个页面中发送一个动作,如下所示:
const dispatch = useDispatch();
useEffect(()=>{
dispatch({type: "SET_URLS"});
},[]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.