javascript - 初学 React Router 请教在 ES6 下 如何实现路由跳转前确认
天蓬老师
天蓬老师 2017-04-11 12:57:34
0
2
1036

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

membalas semua(2)
迷茫
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版本的,其他版本没试

伊谢尔伦

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

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

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!