react-router

掌握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>
			)
		}
			
		/>
	)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值