简体   繁体   English

从并发事件重新渲染后,react-router停止路由

[英]react-router stops routing after rerender from a concurrent event

I have a dropdown that is controlled via state . 我有一个通过state控制的下拉菜单。
Clicking on a button toggles it on. 单击button其打开。 Clicking outside toggles it off. 单击外部将其关闭。

The dropdown contains Links within my application, however, when the dropdown is being toggled off, route transition is prevented. 下拉列表包含我的应用程序中的链接,但是,当关闭下拉列表时,将阻止路由转换。

If autohide is disabled, routing works fine, however, it is desired to also hide the dropdown on route transition . 如果禁用了自动隐藏,则路由工作正常,但是,还希望隐藏路由转换的下拉列表

  1. Please explain to me what is going on 请告诉我发生了什么事
  2. Also please help me fix it 还请帮我解决


在此处输入图片说明

class App extends React.Component {
  state = {
    isNavShown: false
  }

  showNav = () => this.setState({isNavShown: true})

  hideNav = event => {
    // ... some more logic ...
    // don't hide if autoHide is disabled
    if (autoHide.checked === false) return

    this.setState({isNavShown: false})
  }

  componentDidMount() {
    document.addEventListener('mousedown', this.hideNav)
  }

  // ...
} 

I have also tried wrapping the setState in setTimeout , but to no avail. 我也尝试过将setState包装在setTimeout ,但无济于事。

Here is the full jsfiddle https://jsfiddle.net/nimareq/1kh47uey/ 这是完整的jsfiddle https://jsfiddle.net/nimareq/1kh47uey/

So the issue is that your hideNav function is hiding the nav if the user clicks anywhere outside of show navigation button and the checkbox you built. 因此,问题在于,如果用户单击“显示导航”按钮和所构建的复选框之外的任何位置,则hideNav函数将隐藏导航。 However, if the user clicks on the nav itself it will be hidden before you have a chance to navigate the user. 但是,如果用户单击导航本身,则导航将被隐藏,然后才有机会导航用户。

Essentially, the browser will detect the click event listener you made on the document before it bubbles down to the anchor tag click. 从本质上讲,浏览器会检测到您在文档上创建的click事件监听器,然后气泡到锚标记单击。 By the time it gets there the anchor tag is gone. 等到到达锚标签时,锚标签就消失了。 (I hope that makes sense lol) (我希望这很有意义)

Anyways you can easily solve it by adding the following to your hideNav function: 无论如何,您可以通过将以下内容添加到hideNav函数中来轻松解决它:

if(nav.contains(event.target)) return;

Also don't forget to add the id="nav" on your navbar or whatever else you want to call it. 另外,不要忘记在导航栏或其他任何您想调用的名称上添加id =“ nav”。 This way the navbar won't disappear when u click on the navbar. 这样,当您单击导航栏时,导航栏不会消失。 It will still disappear if you click off the navbar. 如果您单击导航栏,它将仍然消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM