javascript - 初学 React Router 请教在 ES6 下 如何实现路由跳转前确认

 CHERRYMJM 发布于 2022-11-09 05:48

根据 React Router 的官方文档:

React Router 提供一个 routerWillLeave 生命周期钩子,这使得 React 组件可以拦截正在发生的跳转,或在离开 route 前提示用户

链接:跳转前确认 | React Router 中文文档

所以我目前是想在一个嵌套得较深的子组件内使用这个 routerWillLeave 钩子,由于我使用了 ES6,组件的代码类似下面这样:

class XXX extends XXX {
 ...
}

export default XXX;

所以没有办法使用文档中的 mixin 方法,我想到了使用 react-mixin,参考 StackOverFlow 写了下面的代码:

import reactMixin from 'react-mixin';
import { withRouter, Lifecycle } from 'react-router'

@reactMixin.decorate(Lifecycle)
class Page extends Component {
  static propTypes = {
    router: PropTypes.object,
    route: PropTypes.object,
  }

  constructor(props, context) {
    super(props, context);
    this.state = {
      unsaved: true,
    }
  }

  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?'
    })
  }
}

export default withRouter(Page)

打断点发现 this.props.route 是 undefined,随后根据文档说明,对顶层组件、父级组件都尝试了进行配置
mixin,但是配置后发现 route 会冲突,希望有解决过这类问题的各路高手能够帮忙。十分感谢

2 个回答
  • 现在 React Router 已经发布 4.0 了,而你看的中文文档还是 0.13 版。

    可以看看这个 https://reacttraining.cn/core...

    2022-11-12 11:01 回答
  • export default class XXX extends React.Component {
        constructor(props) {
            super(props);
            this.props.router.setRouteLeaveHook(
                this.props.route,
                this.routerLeaveInformation
              )
        }
        routerLeaveInformation() {
            return 'You have unsaved information, are you sure you want to leave this page?';
        }
    }
    

    这是v3版本的,其他版本没试

    2022-11-12 11:01 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有