最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get the previous route the user came from in react - Stack Overflow

programmeradmin3浏览0评论

I am trying to get the url of the previous page I came from in react.

So if I came from xxx/register, and am now on ../profile, then how do I log that in the console?

I have no clue where to start. Does anyone know how to do this? Is this possible in react? Should I use js instead?

I am trying to get the url of the previous page I came from in react.

So if I came from xxx./register, and am now on .../profile, then how do I log that in the console?

I have no clue where to start. Does anyone know how to do this? Is this possible in react? Should I use js instead?

Share Improve this question asked Apr 23, 2021 at 19:24 GianlucaGianluca 9901 gold badge16 silver badges41 bronze badges 4
  • if you are using react router then history.goBack(); is what you are looking for. – Medi Commented Apr 23, 2021 at 19:26
  • but with history.goBack(), I cannot log that, because it takes me back to that page no matter what. I pretty much just want to log it, so I can use it in an if statement after – Gianluca Commented Apr 23, 2021 at 19:28
  • If you want to see where the user came from it is stored in document.referrer. This is not framework-specific. If you want to keep the track of routes from within you app. Check out react-router. – webduvet Commented Apr 23, 2021 at 19:38
  • @webduvet appreciate the answer! document.referrer works, but it isn't consistent within the app for paths. I think react-router would be better. Could you point me into the right direction for this one plz :) – Gianluca Commented Apr 23, 2021 at 19:46
Add a ment  | 

2 Answers 2

Reset to default 2

We can access the previous page using useHistory()

import { useHistory } from "react-router-dom";

//...
const history = useHistory();

//...
    <div onClick={() => { history.push( 'pages/previous-page', { from: "previous-page" }) }>
       Previous Page
    </div>

On next page you can check by this code

console.log("Landed on this page from ", history.location.state.from )

First off, you ask in the last sentence if you should use JS instead. React is a JavaScript library, thus you are already using JS and everything that you can do in your current version of JS, you can do in React.

Next, the History ponent is what you're looking for.

Here is a very prehensive guide on history: https://reactrouter./web/api/history.

Basically, you view the history, which is an array, from inside of your ponent. You can then either pull different values from the array or even push new values into the array, such as different pages on your website.

发布评论

评论列表(0)

  1. 暂无评论