小编典典

使用react-router检测路由更改

reactjs

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

我想做的是这样的:

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

URL更新后,有什么方法可以接收来自react-router的回调吗?


阅读 712

收藏
2020-07-22

共1个答案

小编典典

history.listen()尝试检测路线变化时,可以使用功能。考虑到您正在使用react- router v4,请用withRouterHOC 包装您的组件以访问history道具。

history.listen()返回一个unlisten函数。您将使用它来unregister收听。

您可以像这样配置路线

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

从历史文档

您可以使用收听当前位置的更改 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接口的子集,包括:

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

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

location.state- 此位置的某些其他状态,不在URL中(在createBrowserHistory和中
受支持createMemoryHistory

location.key-代表此位置的唯一字符串(createBrowserHistory和中支持createMemoryHistory

该操作是PUSH, REPLACE, or POP取决于用户如何访问当前URL的操作之一。

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

您可以配置和使用您的路线,例如

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>
        )
    }
}
2020-07-22