How does react-router4 monitor route jump events and execute the specified method after each route switch?

In

router life cycle
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
each hook function is executed only once. How to listen for route changes when switching react-router, and then execute the specified method?
see onUpdate in react-router "s API (it will be called when the state of the route needs to be updated when the URL changes), but how exactly do I use it, and where do I put it in the router?

Mar.02,2021

We usually use a state manager, such as react-redux, where store has a subscriptions to listen for route changes.
it is recommended that you use encapsulated react-redux dvajs


https://github.com/ReactTrain.

the method history.listen (), which uses history directly, automatically triggers when you switch routes

import createHistory from "history/createBrowserHistory"

const history = createHistory()

// Get the current location.
const location = history.location

// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.pathname, location.state)
})

// Use push, replace, and go to navigate around.
history.push("/home", { some: "state" })

// To stop listening, call the function returned from listen().
unlisten()

it's not necessary, just use componentDidUpdate.

Menu