使用 react-router 检测路由变化

新手上路,请多包涵

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

我想做的是这样的:

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

当 URL 更新时,有什么方法可以从 react-router 接收回调?

原文由 Aris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您可以在尝试检测路由更改时使用 history.listen() 功能。考虑到您正在使用 react-router v4 ,请使用 withRouter HOC 包装您的组件以访问 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()` 来自 `history` 包,如上所述,或者您也可以使用 `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>
    )
}

}

”`

原文由 Shubham Khatri 发布,翻译遵循 CC BY-SA 4.0 许可协议

React Router 5.1+ 的更新。

 import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function SomeComponent() {
  const location = useLocation();

  useEffect(() => {
    console.log('Location changed');
  }, [location]);

  ...
}

原文由 onosendi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进