Detect Route Change with react-router

前端 未结 8 1055
南笙
南笙 2020-11-27 11:18

I have to implement some business logic depending on browsing history.

What I want to do is something like this:

reactRouter.onUrlChange(url => {
         


        
8条回答
  •  日久生厌
    2020-11-27 12:12

    react-router v6

    In the upcoming v6, this can be done by combining the useLocation and useEffect hooks

    import { useLocation } from 'react-router-dom';
    
    const MyComponent = () => {
      const location = useLocation()
    
      React.useEffect(() => {
        // runs on location, i.e. route, change
        console.log('handle route change here', location)
      }, [location])
      ...
    }
    

    For convenient reuse, you can do this in a custom useLocationChange hook

    // runs action(location) on location, i.e. route, change
    const useLocationChange = (action) => {
      const location = useLocation()
      React.useEffect(() => { action(location) }, [location])
    }
    
    const MyComponent1 = () => {
      useLocationChange((location) => { 
        console.log('handle route change here', location) 
      })
      ...
    }
    
    const MyComponent2 = () => {
      useLocationChange((location) => { 
        console.log('and also here', location) 
      })
      ...
    }
    

    If you also need to see the previous route on change, you can combine with a usePrevious hook

    const usePrevious(value) {
      const ref = React.useRef()
      React.useEffect(() => { ref.current = value })
    
      return ref.current
    }
    
    const useLocationChange = (action) => {
      const location = useLocation()
      const prevLocation = usePrevious(location)
      React.useEffect(() => { 
        action(location, prevLocation) 
      }, [location])
    }
    
    const MyComponent1 = () => {
      useLocationChange((location, prevLocation) => { 
        console.log('changed from', prevLocation, 'to', location) 
      })
      ...
    }
    

    It's important to note that all the above fire on the first client route being mounted, as well as subsequent changes. If that's a problem, use the latter example and check that a prevLocation exists before doing anything.

提交回复
热议问题