How does react get the address switched by the browser?

recently encountered a problem. I use react-router-dom and want to know the address information of the address bar when I switch
clipboard.png
.
I try to use the lifecycle but can"t solve
I originally wanted to use onhashchange but react didn"t. Ask for help
. To put it simply, I just want to know how react gets the url of address switching changes

.
Feb.07,2022

I don't know if you use things like redux .
if you give route r to redux management, you can see the current url path
directly in this.props . If not, then you can directly print console.log (location) in render .


react-router uses history api


I have found a solution myself, I use window.onhashchange, but this method can only be used in HashRouter routing with BrowserRouter routing without practice

let that = this
window.onhashchange = function () {
  that.setState({
    pathname: window.location.hash.substr(1)
  })
}

so I can load components through pathname changes. Do you think this is okay?
ask for advice! A small black classmate who has just learned react:)


you can try the high-level component withRouter of react-router to get routing information.

Menu