掌握react-router
react-router
Switch, BrowserRouter, Route, Link
npm install --save react-router-dom
class Example extends React.Component {
render(){
return(
<BrowserRouter>
<nav>
<Link to="/">商品列表</Link>
<Link to="/manage">商品管理</Link>
</nav>
<Route exact path="/" component={ProductList}></Route>
<Route path="/manage" component={ProductManage}></Route>
<Route path="/detail/:id" component={Detail}></Route>
</BrowserRouter>
)
}
}
// 实现路由嵌套
function ProductManage(){
return(
<div>
<h1>商品管理</h1>
<Link to="/manage/a">go a</Link>
<Link to="/manage/b">go b</Link>
<Route path="/manage/a" component={()=><h2>a</h2>}></Route>
<Route path="/manage/b" component={()=><h2>b</h2>}></Route>
</div>
)
}
// 路由可以接收参数
function Detail({ match, history, location }) {
console.log(match, history, location);
return (
<div>
ProductMgt
<p>{match.params.name}</p>
</div>
);
}
404
设定一个没有path的路由在路由列表最后面,表示一定匹配
{
/* 添加Switch表示仅匹配一个 */}
<Switch>
{/* 首页重定向换成Route方式处理避免影响404 */}
<Route exact path="/" render={props => <Redirect to="/list" />} />
{/* <Redirect to="/list"></Redirect> */}
<Route component={() => <h3>页面不存在</h3>}></Route>
</Switch>
路由守卫
<PravateRoute path="/manage" component={ProductManage} isLogin={false}/>
<Route path="/login" component={Login}>
// 我要渲染的是component里的东西,所以要做一个解构, ...rest表示剩余项待用
function PravateRoute({component:Component, ...rest}){ // Component别名,jsx不支持小写
return(
// 官方提供render来进行条件渲染,render里是一个函数,接收一个props
// 返回你要渲染的组件
<Route render={
// props就等于{match, history, location}
props=> isLogin ? (
<Component></Component>
) : (
// 做一个重定向,这是最简单的写法,但是,将来登陆完还有个回跳
<Redirect to='/login'></Redirect>
// 回跳的话需要接受一个location对象,属性至少给个pathname
// 状态state用来传参,传任意复杂的参数
<Redirect to={{pathname:'/login',
state:{redirect:props.location.pathname }}}>
</Redirect>
)
}
/>
)
}