什么是路由
路由是根据不同的 url 地址展示不同的内容或页面。
一个针对React而设计的路由解决方案、可以友好的帮你解决React components 到URl之间的同步映射关系
安装路由
https://react-router.docschina.org/
npm install react-router-dom@5
使用路由
导入路由方法
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
定义路由重定向
<HashRouter>
<Switch>
<Route path="/films" component={Films}/>
<Route path="/cinemas" component={Cinemas}/>
<Route path="/center" component={Center}/>
<Redirect from="/" to="/films" />
{/* <Redirect from="/" to="/films" exact/>
<Route path="*" component={NotFound}/> */}
</Switch>
</HashRouter>
注:
-
exact 精确匹配 (Redirect 即使使用了exact, 外面还要嵌套Switch 来用)
-
Warning: Hash history cannot PUSH the same path; a new entry will not be added to the history stack,这个警告只有在hash 模式会出现。
嵌套路由
<Switch>
<Route path="/films/nowplaying" component={Nowplaying}/>
<Route path="/films/comingsoon" component={Comingsoon}/>
<Redirect from="/films" to="/films/nowplaying"/>
</Switch>
路由跳转方式
- 声明式导航
<NavLink to="/films" activeClassName="active">films</NavLink>
<NavLink to="/cinemas" activeClassName="active">cinemas</NavLink>
<NavLink to="/center" activeClassName="active">center</NavLink>
- 编程式导航
this.props.history.push(`/center`)
路由传参
//传递参数
this.props.history.push({ pathname : '/user' ,query : { day: 'Friday'} })
//接收参数
this.props.location.query.day
(2)
//传递参数
this.props.history.push({ pathname:'/user',state:{day : 'Friday' } })
//接收参数
this.props.location.state.day
路由拦截
//isAuth()为判断方法
<Route path="/center" render={()=>isAuth()?<Center/>:<Login/>}/>
withRouter
原理:
高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.
import React from 'react'
import './nav.css'
import {
NavLink,
withRouter
} from "react-router-dom"
class Nav extends React.Component{
handleClick = () => {
// Route 的 三个对象将会被放进来, 对象里面的方法可以被调用
console.log(this.props);
}
render() {
return (
<div className={'nav'}>
<span className={'logo'} onClick={this.handleClick}>掘土社区</span>
<li><NavLink to="/" exact>首页</NavLink></li>
<li><NavLink to="/activities">动态</NavLink></li>
<li><NavLink to="/topic">话题</NavLink></li>
<li><NavLink to="/login">登录</NavLink></li>
</div>
);
}
}
// 导出的是 withRouter(Nav) 函数执行
export default withRouter(Nav)
所以withRouter的作用就是, 如果我们某个东西不是一个Router, 但是我们要依靠它去跳转一个页面, 比如点击页面的logo, 返回首页, 这时候就可以使用withRouter来做.
在这个例子中, 我将span使用withRouter作为一个可点击跳转的Link
反向代理
解决跨域问题
npm install http-proxy-middleware --save
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};