react路由react-router
安装
首先通过 npm 安装:
$ npm install --save react-router
Route渲染内容的三种⽅式
Route渲染优先级:children>component>render。
这三种⽅式互斥,只能⽤⼀种。
children:function函数
有时候,不管location是否匹配,你都需要渲染⼀些内容,这时候你可以⽤children。
除了不管location是否匹配都会被渲染之外,其它⼯作⽅法与render完全⼀样。
render:function函数
但是当⽤render的时候,调⽤的只是个函数。
只在当location匹配的时候渲染。
component: component
只在当location匹配的时候渲染。
ReactJS 的5种路由模式
我们一直在使用的路由方式是BrowserRouter,也就是浏览器的路由方式,其实React还有几种路由方式:
1、BrowserRouter:浏览器的路由方式,也就是在开发中最常使用的路由方式
2、HashRouter:在路径前加入#号成为一个哈希值,Hash模式的好处是,再也不会因为我们刷新而找不到我们的对应路径
3、MemoryRouter:不存储history,所有路由过程保存在内存里,不能进行前进后退,因为地址栏没有发生任何变化
4、NativeRouter:经常配合ReactNative使用,多用于移动端
5、StaticRouter:设置静态路由,需要和后台服务器配合设置,比如设置服务端渲染时使用
404⻚⾯
设定⼀个没有path的路由在路由列表最后⾯,表示⼀定匹配
{/* 添加Switch表示仅匹配⼀个*/}
{/* 根路由要添加exact,实现精确匹配 */}
//注意:路由中随便输入时,返回这个页面,如果没有Switch,则所有页面下边都显示这个404页面,且404页面必须放在最后,否则只显示404页面
class EmptyPage extends Component {
render() {
return (
EmptyPage-404
跳转前确认
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?’
},
// …
})
如果你想在一个深层嵌套的组件中使用 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
}
})
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?’
},
// …
})