【问题标题】:warning in react-router dom when user tries to navigate away from the site当用户尝试离开站点时,react-router dom 中的警告
【发布时间】:2017-10-01 23:54:04
【问题描述】:

我有一个多步向导,每一步都有一个 react-router 路由。

目前,如果用户导航到外部链接,他们将失去所有状态。

react-router-dom 或 react-router 中是否有一个可以警告用户并允许他们取消的功能?

【问题讨论】:

  • 您能否为每个外部链接添加一个类,以便您可以附加一个在单击时触发提示的事件侦听器?您可以制作一个外部链接组件。
  • react router dom 现在依赖于 react 的生命周期。如果它正在导航离开 componentWillUnmount 可能会被用来捕捉它?

标签: reactjs react-router react-router-dom


【解决方案1】:

为此有一个组件。在此处查看提示组件: https://reacttraining.com/react-router/core/api/Prompt

这是他们使用的示例:

<Prompt
    when={formIsHalfFilledOut} // <- function that returns boolean
    message="Are you sure you want to leave?"
/>

【讨论】:

    【解决方案2】:

    我认为您正在寻找 React Router 的历史 API 下的阻塞转换。

    根据反应路由器历史 github 页面上的示例:

    您可以注册一个简单的提示消息,该消息将显示给 用户离开当前页面之前。

    const unblock = history.block('Are you sure you want to leave this page?')
    

    详细信息https://github.com/ReactTraining/history#properties

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2021-01-01
      • 2023-01-26
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多