【问题标题】:Prevent component from unmounting - showing notification to users before opening other component防止组件卸载 - 在打开其他组件之前向用户显示通知
【发布时间】:2017-05-18 13:11:15
【问题描述】:

在我的网络应用程序中,有一个用户输入数据的表单。如果他们想导航到其他组件或返回,我想通知他们对表单进行了更改并向他们显示确认对话框。 如果用户单击表单顶部的后退按钮,我知道如何实现这一点,但是当用户单击侧边栏菜单选项时,我不知道如何处理它。 (有一个带有多个指向其他组件的链接的侧边栏 - 使用 react-router)。

我已经尝试过使用 componentWillunmount() 但没有运气,因为组件在任何情况下都会被卸载。

如果有人有这方面的经验,我真的需要一些帮助。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-router


    【解决方案1】:

    试试 routerWillLeave 钩子,这里是 react-router 文档中的一个例子:

    const Home = withRouter(
      React.createClass({
    
        componentDidMount() {
          this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
        },
    
        routerWillLeave(nextLocation) {
          // return false to prevent a transition w/o prompting the user,
          // or return a string to allow the user to decide:
          if (!this.state.isSaved)
            return 'Your work is not saved! Are you sure you want to leave?'
        },
    
        // ...
    
      })
    )
    

    https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

    【讨论】:

    • 非常感谢,正是我需要的。
    猜你喜欢
    • 2011-04-21
    • 2020-01-06
    • 2018-10-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多