React路由
根据不同的路径,显示不同的组件(内容);React使用的库react-router-dom;
安装:
Cnpm install react-router-dom --save
react三大组件
ReactRouter三大组件:
Router:所有路由组件的根组件(底层组件),包裹路由规则的最外层容器。
属性:basename->设置跟此路由根路径,router可以在1个组件中写多个。
Route:路由规则匹配组件,显示当前规则对应的组件
Link:路由跳转的组件
注意:如果要精确匹配,那么可以在route上设置exact属性。
路由的使用
1.导出(引用)
import React from 'react';
//hash模式
//import {HashRouter as Router,Link,Route} from 'react-router-dom'
//history模式/后端匹配使用
import {BrowserRouter as Router,Link,Route} from 'react-router-dom'
2.路由配置
<Router>
<Route path="/" exact component={()=>(<div>首页</div>)}></Route>
<Route path="/me" component={()=>(<div>me</div>)}></Route>
<Route path="/product" component={()=>(<div>product</div>)}></Route>
/*动态路由配置*/
<Route path="/news/:id" component={News}></Route>
</Router>
3.link组件的使用
概述: Link组件可以设置to属性来进行页面的跳转,to属性可以直接写路径的字符串,也可以通过1个对象,进行路径的设置.
let meObj = {
pathname:"/me",//跳转的路径
search:"?username=admin",//get请求参数
hash:"#abc",//设置的HASH值
state:{msg:'helloworld'}//传入组件的数据
};
<Router>
<Link to="/">Home</Link>
<Link to={ meObj }>个人中心</Link>
</Router>
Link的replace属性:点击链接后,将新地址替换成历史访问记录的原地址。
重定向组件
如果访问某个组件时,如果有重定向组件,那么就会修改页面路径,使得页面内容显示为所定向路径的内容
function LoginInfo(props){
//props.loginState = 'success';
//props.loginState = "fail"
console.log(props)
if(props.location.state.loginState === 'success'){
return <Redirect to="/admin"></Redirect>
}else{
return <Redirect to="/login"></Redirect>
}
}
switch组件
让switch组件内容的route只匹配1个,只要匹配到了,剩余的路由规则将不再匹配
<Router>
<Switch>
<Route path="/" exact component={()=>(<h1>首页</h1>)}></Route>
<Route path="/form" exact component={FormCom}></Route>
</Switch>
</Router>