$ npm i react-router-dom --save
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
// 声明路由组件 一个func 相当于是一个路由组件
// 这里是无状态路由的写法 实际工作中会把路由组件单独的写成一个js来进行引入
function Index (){
return <h2>Jspang.com</h2>
}
function List (){
return <h2>List-page</h2>
}
function AppRouter (){
return(
<Router>
<ul>
{/* Link 为路由的跳转 类似于a标签 */}
<li><Link to='/'>首页</Link></li>
</ul>
{/* exact 为精准定位 必须为/ 才能进行匹配
Route 为路径的指引
component 为上面绑定的组件
path 为路径
*/}
<Route path="/" exact component = {Index} />
{/* :id 设置规则 不传不跳转 */}
<Route path="/list/:id" component = {List} />
<Route path="/home/" component = {Home} />
</Router>
)
}
// 暴露出去
export default AppRouter;
<Route path="/list/:id" component = {List} />
// 在生命周期中接收 路由传递的值
componentDidMount(){
let ReadID = this.props.match.params.id
console.log(ReadID)
}
import {Link,Redirect } from 'react-router-dom'
编程式重定向
this.props.history.push('/home/')
标签重定向 在render最外层标签中写入
<Redirect to="/home/" />
模拟一组数据
let routeConfig =[
{path:'/',title:'博客首页',exact:true,component:Index},
{path:'/video/',title:'视频教程',exact:false,component:Video},
{path:'/work/',title:'职场技能',exact:false,component:Work}
]
return(
<Router>
<div className="mainDiv">
<div className="leftNav">
<h3>一级导航</h3>
<ul>
{
routeConfig.map((item,index)=>{
return (
<li key={index}>
<Link to={item.path}>{item.title}</Link>
</li>
)
})
}
</ul>
</div>
</div>
<div className="rightMain">
{
routeConfig.map((item,index)=>{
return (
<Route path={item.path}
exact={item.exact}
component={item.component} />
)
})
}
</div>
</Router>