余温react前端开发那些事儿

react路由-react路由的跳转以及路由信息

2020-12-04  本文已影响0人  lucky_yao

课程目标

  1. 熟悉掌握路由的配置
  2. 熟悉掌握跳转路由的方式
  3. 熟悉掌握路由跳转传参的方式
  4. 可以根据对其的理解封装一个类似Vue的router-view

知识点

  1. 路由的配置属性
  1. 路由的跳转形式

<ul>
  <li><NavLink exact to="/" activeStyle={{
           fontWeight: 'bold',
           color: 'red'
         }}>home</NavLink>
  </li>
  <li><NavLink exact to="/detail" activeStyle={{
          fontWeight: 'bold',
          color: 'red'
         }}>detail</NavLink>
  </li>
</ul>


<ul>
  <li onClick={() => this.props.history.push({pathname:'detail'})}><div>home</div>
  </li>
  <li onClick={() => this.props.history.push({pathname:'home'})}><div>detail</div>
  </li>
</ul>

  1. 跳转传参

<ul>
  <li><NavLink exact to="/" activeStyle={{
           fontWeight: 'bold',
           color: 'red'
         }}>home</NavLink>
  </li>
  <li><NavLink exact to={{pathname:'detail',state:{id:2}}} activeStyle={{
          fontWeight: 'bold',
          color: 'red'
         }}>detail</NavLink>
  </li>
</ul>


<ul>
  <li onClick={() => this.props.history.push({pathname:'detail',state:{id:1}})}><div>home</div>
  </li>
  <li onClick={() => this.props.history.push({pathname:'home',state:{
  id:0}})}><div>detail</div>
  </li>
</ul>

// 获取参数
this.props.history.location.state

  1. 传递的参数分类
1.使用query传递  
   this.props.history.push({ pathname : '/access_control/role/roleEdit',query:{ aa: 'aa'} })
 获取参数:
   this.props.location.query.aa
2.使用state传递
 this.props.history.push({ pathname : '/access_control/role/roleEdit',state:{ aa: 'aa'} })
 获取参数:
   this.props.location.state.aa
 
 
  state传的参数是加密的,query传的参数是公开的,在地址栏
  1. 封装RouterView
class RouterView extends Component {
    render () {
        let {
            routes
        } = this.props;
        let redir = routes && routes.length > 0 && routes.filter((v, i) => {
            return v.redirect
        })
        let renderRedir = redir.length > 0 && redir.map((v, i) => {
            return <Redirect from={v.path} to={v.redirect} key={i} />
        })
        return (
            <Switch>
                {
                    routes && routes.length > 0 && routes.map((v, i) => {
                        if (v.component) {
                            return <Route key={i} path={v.path} component={(props) => {
                                return <v.component routes={v.children} {...props} />
                            }} />
                        }
                    }).concat(renderRedir)
                }
            </Switch>
            
        )
路由跳转、路由信息.png
上一篇 下一篇

猜你喜欢

热点阅读