如何使用react-router v4检测路由变化?

Hun*_*Liu 8 reactjs react-router react-router-dom

我需要检测是否发生了路由更改,以便我可以将变量更改为true.

我已经通过这些问题看:
1. https://github.com/ReactTraining/react-router/issues/3554
2. 如何收听路线的变化做出反应路由器V4?
3. 使用react-router检测路由更改

他们都没有为我工作.路由发生更改时是否有明确的方法来调用函数.

wdm*_*wdm 18

一种方法是使用withRouter高阶分量.

现场演示(单击超链接以更改路线并在显示的控制台中查看结果)

您可以通过withRouter高阶组件访问历史对象的属性和最接近的匹配.withRouter会在呈现时将更新的匹配,位置和历史道具传递给包装组件.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

import {withRouter} from 'react-router-dom';

class App extends Component {
    componentDidUpdate(prevProps) {
        if (this.props.location.pathname !== prevProps.location.pathname) {
            console.log('Route change!');
        }
    }
    render() {
        return (
            <div className="App">
                ...routes
            </div>
        );
    }
}

export default withRouter(props => <App {...props}/>);
Run Code Online (Sandbox Code Playgroud)

另一个使用url params的例子:

如果你改变从曲线路线/profile/20/profile/32

你的路线被定义为 /profile/:userId

componentDidUpdate(prevProps) {
    if (this.props.match.params.userId !== prevProps.match.params.userId) {
        console.log('Route change!');
    }
}
Run Code Online (Sandbox Code Playgroud)


par*_*rse 7

使用React Hooks,它应该很简单:

useEffect(() => {
    const { pathname } = location;
    console.log('New path:', pathname);
}, [location.pathname]);
Run Code Online (Sandbox Code Playgroud)

通过传递location.pathname第二个数组参数,意味着您要使用useEffect仅在location.pathname发生更改时重新运行。

带有代码源的实时示例:https : //codesandbox.io/s/detect-route-path-changes-with-react-hooks-dt16i


Tha*_*yen 6

由于钩子,React Router v5 现在可以自动检测路由变化。以下是背后团队的示例

import { Switch, useLocation } from 'react-router'

function usePageViews() {
  let location = useLocation()

  useEffect(
    () => {
      ga.send(['pageview', location.pathname])
    },
    [location]
  )
}

function App() {
  usePageViews()
  return <Switch>{/* your routes here */}</Switch>
}
Run Code Online (Sandbox Code Playgroud)

ga每次 URL 更改时,此示例都会向 Google Analytics ( )发送“页面浏览量” 。

  • 问题是它在同一路线上更新,因为 location.key 每次都会改变。如果有什么需要在效果中监听 location.pathname (4认同)