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

查看:132
本文介绍了javascript - 初学 React Router 请教在 ES6 下 如何实现路由跳转前确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

根据 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 会冲突,希望有解决过这类问题的各路高手能够帮忙。十分感谢

解决方案

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版本的,其他版本没试

这篇关于javascript - 初学 React Router 请教在 ES6 下 如何实现路由跳转前确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆