如何使用 react-router v4 检测路由变化? [英] How to detect route changes with react-router v4?

查看:47
本文介绍了如何使用 react-router v4 检测路由变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我已经浏览了这些问题:
1. https://github.com/ReactTraining/react-router/issues/3554
2.
如何在react router v4中监听路由变化?
3. 使用 react-router 检测路由变化

他们都没有为我工作.有没有明确的方法在发生路由变化时调用函数.

解决方案

一种方法是使用 withRouter 高阶组件.

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

<块引用>

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

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

import {withRouter} from 'react-router-dom';类 App 扩展组件 {componentDidUpdate(prevProps) {if (this.props.location.pathname !== prevProps.location.pathname) {console.log('路由改变!');}}使成为() {返回 (<div className="应用程序">...路线

);}}export default withRouter(props => <App {...props}/>);

<小时>

另一个使用 url 参数的例子:

如果您将配置文件路由从 /profile/20 更改为 /profile/32

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

componentDidUpdate(prevProps) {if (this.props.match.params.userId !== prevProps.match.params.userId) {console.log('路由改变!');}}

I need to detect if a route change has occurred so that I can change a variable to true.

I've looked through these questions:
1. https://github.com/ReactTraining/react-router/issues/3554
2. How to listen to route changes in react router v4?
3. Detect Route Change with react-router

None of them have worked for me. Is there a clear way to call a function when a route change occurs.

解决方案

One way is to use the withRouter higher-order component.

Live demo (click the hyperlinks to change routes and view the results in the displayed console)

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

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}/>);


Another example that uses url params:

If you were changing profile routes from /profile/20 to /profile/32

And your route was defined as /profile/:userId

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

这篇关于如何使用 react-router v4 检测路由变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆