在 React 16 / Router V4 中显示抽屉时如何覆盖后退按钮

How to override Back button when a drawer is showing in React 16 / Router V4

我有这样的结构,有这样的路线:

<Route path="/sample-route" component={ComponentA}/>

然后 ComponentA 有:

<ComponentA>
  <ComponentB/>
  <ComponentC>
    <MaterialUIDrawer/>
  </ComponentC>
</ComponentA>

ComponentC小时候在5条不同的路线中使用。 MaterialUIDrawer 基于 redux reducer 中的标志显示。我要解决的问题是当抽屉打开时,单击后退会隐藏它但也会导航回来。我试过这样解决它:

window.onpopstate = (e) => {
   if (this.props.isOpen) {
     this.props.toggleDrawer(false);
     this.props.history.replace(this.props.match.url);
   }
 };

这有两个问题:

我也试过在ComponentC中设置一个<Route/>,然后抽屉就住在那里,但我没成功,可能路径不对。感觉这可能是正确的方法,如果路径是 /path1,那么抽屉位于 /path1/drawer,或 /path2/drawer,等等

我正在尝试为浏览器中的后退按钮找到一种关闭抽屉的方法(因此执行我定义的功能)并覆盖默认功能。

我认为你应该在这里使用 props 而不是路径,比如 /path1?drawer=1,但是你肯定需要使用 history/location 这样后退按钮才能真正返回,所以你走在正确的道路上。

我不确定您使用的浏览器历史记录管理器是什么,但我建议您不要使用它,而不是依靠 window 弹出状态。你的 history 模块应该是真实的来源和 feed redux,而不是 IMO 的其他方式。