开发指南 开发指南
React Router 中文文档
TypeScript 中文文档
gitee (opens new window)
React Router 中文文档
TypeScript 中文文档
gitee (opens new window)
  • 首页
  • 1、简介
  • 2、基础
    • 路由配置
    • 路由匹配原理
    • History
    • 默认路由(IndexRoute)与 IndexLink
  • 3、高级用法
    • 动态路由
    • 跳转前确认
    • 服务端渲染
    • 组件生命周期
    • 组件外部跳转
  • 4、升级指南
  • 5、排错
  • 6、API文档
  • 7、词汇表

# 跳转前确认

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

  1. return false 取消此次跳转
  2. return 返回提示信息,在离开 route 前提示用户进行确认。

你可以在 route 组件 中引入 Lifecycle mixin 来安装这个钩子。

import { Lifecycle } from 'react-router'

const Home = React.createClass({

  // 假设 Home 是一个 route 组件,它可能会使用
  // Lifecycle mixin 去获得一个 routerWillLeave 方法。
  mixins: [ Lifecycle ],

  routerWillLeave(nextLocation) {
    if (!this.state.isSaved)
      return 'Your work is not saved! Are you sure you want to leave?'
  },

  // ...

})

如果你在组件中使用了 ES6 类,你可以借助 react-mixin (opens new window) 包将 Lifecycle mixin 添加到组件中,不过我们推荐使用 React.createClass 来创建组件,初始化路由的生命周期钩子函数。

如果你想在一个深层嵌套的组件中使用 routerWillLeave 钩子,只需在 route 组件 中引入 RouteContext mixin,这样就会把 route 放到 context 中。

import { Lifecycle, RouteContext } from 'react-router'

const Home = React.createClass({

  // route 会被放到 Home 和它子组件及孙子组件的 context 中,
  // 这样在层级树中 Home 及其所有子组件都可以拿到 route。
  mixins: [ RouteContext ],

  render() {
    return <NestedForm />
  }

})

const NestedForm = React.createClass({

  // 后代组件使用 Lifecycle mixin 获得
  // 一个 routerWillLeave 的方法。
  mixins: [ Lifecycle ],

  routerWillLeave(nextLocation) {
    if (!this.state.isSaved)
      return 'Your work is not saved! Are you sure you want to leave?'
  },

  // ...

})

← 动态路由 服务端渲染 →

内容转载自开源项目React Router中文文档
React Router 中文文档 | 赣公网安备 36012102000277号 | 赣ICP备2021002441号-2