千锋学习视频https://www.bilibili.com/video/BV1dP4y1c7qd?p=72&spm_id_from=pageDriver&vd_source=f07a5c4baae42e64ab4bebdd9f3cd1b3
路由是根据不同的 url 地址展示不同的内容或页面。
一个针对React而设计的路由解决方案、可以友好的帮你解决React components 到URl之间的同步映射关系。
npm i react-router-dom@5
import React, { Component } from 'react'
import {HashRouter,Route} from 'react-router-dom'
import Film from './views/Film'
import Cinemas from './views/Cinemas'
import Center from './views/Center'
export default class componentName extends Component {
render() {
return (
)
}
}
也可以把路由封装成一个组件抽离出去
import React, { Component } from 'react'
import MyRouter from './MyRouter'
// import Film from './views/Film'
// import Cinemas from './views/Cinemas'
// import Center from './views/Center'
export default class componentName extends Component {
render() {
return (
{/* 也可以把路由封装成一个组件抽离出去
*/}
)
}
}
import React, { Component } from 'react'
import {HashRouter,Route} from 'react-router-dom'
import Film from './views/Film'
import Cinemas from './views/Cinemas'
import Center from './views/Center'
export default class MyRouter extends Component {
render() {
return (
)
}
}
如果没有匹配的路径,需要跳转到指定的路径 使用
import React, { Component } from 'react'
import {HashRouter,Route,Redirect,Switch} from 'react-router-dom'
import Film from './views/Film'
import Cinemas from './views/Cinemas'
import Center from './views/Center'
export default class MyRouter extends Component {
render() {
return (
{/* 匹配/路径的时候 模糊匹配 跳转到/films */}
)
}
}
但是这个做法存在问题:当输入http://localhost:3000/#/center 会跳到center 但再次刷新又会跳到/films
改进:使用Switch 匹配一次后将不再继续匹配
import React, { Component } from 'react'
import { HashRouter, Route, Redirect, Switch } from 'react-router-dom'
import Film from './views/Film'
import Cinemas from './views/Cinemas'
import Center from './views/Center'
export default class MyRouter extends Component {
render() {
return (
{/* 匹配/路径的时候 跳转到/films */}
)
}
}
精准匹配exact
场景:/ 跳转到/films 其他不匹配上述路由的跳转到404
import React, { Component } from 'react'
import { HashRouter, Route, Redirect, Switch } from 'react-router-dom'
import Film from './views/Film'
import Cinemas from './views/Cinemas'
import Center from './views/Center'
import NotFound from './views/NotFound'
export default class MyRouter extends Component {
render() {
return (
{/* 匹配/路径的时候 跳转到/films */}
)
}
}
import React, { Component } from 'react'
export default class NotFound extends Component {
render() {
return (
404 Not Found
)
}
}
注意:exact 精确匹配 (Redirect 即使使用了exact, 外面还要嵌套Switch 来用)
MyRouter组件中的路由保持不变 当/film模糊匹配到后会进入Film组件
以下代码在Film组件中写即可
1.声明式导航
import React, { Component } from 'react'
import {NavLink} from 'react-router-dom'
export default class Navbar extends Component {
render() {
return (
电影
影院
我的
)
}
}
意思是可以监听到地址 如果是/center会给我的这个a标签给加上class="active"的属性,
也可以自定义属性,方便设置css高亮显示
电影
影院
我的
2.编程式导航
this.props.history.push(`/center`)
或者导入useHistory
import {useHistory} from 'react-router-dom'
const history =useHistory()
history.push(`/detail`)