加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 使用react-router检测用户离开页面

发布时间:2020-12-15 20:55:42 所属栏目:百科 来源:网络整理
导读:我希望我的ReactJS应用程序在导航离开特定页面时通知用户。特别是弹出消息,提醒他/她做一个动作: “Changes are saved,but not published yet. Do that now?” 我应该在react-router上全局触发这个,还是可以从react页面/组件中做到这一点? 我没有在后者
我希望我的ReactJS应用程序在导航离开特定页面时通知用户。特别是弹出消息,提醒他/她做一个动作:

“Changes are saved,but not published yet. Do that now?”

我应该在react-router上全局触发这个,还是可以从react页面/组件中做到这一点?

我没有在后者身上找到任何东西,我宁愿避开第一个。除非它当然是标准,但这让我想知道如何做这样的事情,而不必将代码添加到用户可以去的每个其他可能的页面..

欢迎任何见解,谢谢!

对于react-router 2.4.0

注意:建议将所有代码迁移到最新的react-router以获取所有新的好东西。

按照react-router documentation的建议:

应该使用withRouter更高阶组件:

We think this new HoC is nicer and easier,and will be using it in
documentation and examples,but it is not a hard requirement to
switch.

作为文档中的ES6示例:

import React from 'react'
import { withRouter } from 'react-router'

const Page = React.createClass({

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route,() => {
      if (this.state.unsaved)
        return 'You have unsaved information,are you sure you want to leave this page?'
    })
  }

  render() {
    return <div>Stuff</div>
  }

})

export default withRouter(Page)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读