在加载新页面时响应状态更改或页面刷新

React state change or page refresh on loading new page

我有一个带有汉堡菜单的 React 应用程序,它在页面内容上方 in/out 滑动。我连接了 redux 来处理侧边菜单状态,它切换 类 用于正文和覆盖以防止滚动。

当侧边菜单处于活动状态时,我单击其中的一个导航链接,页面确实加载了新页面,但侧边菜单仍然打开。

我目前在 App.js

中使用 BrowserRouterSwitchRoute

导航到新页面时如何更改状态?

我考虑的一些事情是:

有没有更好的方法?我不想将 onClick 事件添加到侧边菜单中的所有项目,因为它稍后会增长,我也不想将 componentDidMount 添加到每个页面。

您可以将路由器连接到您的菜单组件并检测位置变化:

class Menu extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location.pathname !== prevProps.location.pathname) {
      /** change redux state here */
    }
  }

  ....
}

export default withRouter(Menu);