使用 react-router 检测路由变化 [英] Detect Route Change with react-router

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

问题描述

我必须根据浏览历史实现一些业务逻辑.

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

我想做的是这样的:

reactRouter.onUrlChange(url => {
   this.history.push(url);
});

当 URL 更新时,有没有办法从 react-router 接收回调?

Is there any way to receive a callback from react-router when the URL gets updated?

推荐答案

您可以使用 history.listen() 函数试图检测路线变化.考虑到您使用的是 react-router v4,请使用 withRouter HOC 包装您的组件以访问 history 道具.

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() 返回一个 unlisten 函数.您可以使用它来取消注册收听.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

你可以像这样配置你的路由

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

然后在 AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

来自历史docs:

您可以使用以下命令监听当前位置的更改history.listen:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

location 对象实现了 window.location 的一个子集界面,包括:

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

位置还可能具有以下属性:

Locations may also have the following properties:

location.state - 此位置的一些额外状态,不在 URL 中(在 createBrowserHistorycreateMemoryHistory)

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - 表示此位置的唯一字符串(支持在 createBrowserHistorycreateMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

动作是 PUSH、REPLACE 或 POP 之一,具体取决于用户如何到达当前网址.

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

当您使用 react-router v3 时,您可以使用 history 包中的 history.listen() 如上所述,或者您也可以使用 browserHistory.listen()

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

你可以像这样配置和使用你的路由

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 

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

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