React路由

React路由

安装

如果想要使用react路由,则需要安装react-router-dom

在该模块中,我们会经常使用BrowserRouterHashRouterRouteSwitchRedirectLinkNavLink

使用

import React, { Component } from 'react'
import { HashRoter as Router, Route } from 'react-router-dom'

class Router extends Component {
  constructor (props) {
    super(props)
    
  } 

  render () {
    reture (
      <Router>
        // 每个路由配置都是一个Route
        <Route exact path="/" component={}></Route>
        <Route></Route>
        <Route></Route>
        <Route></Route>
      </Router>
    )
  }
}

嵌套路由

import React, { Component } from 'react'
import { HashRoter as Router, Route } from 'react-router-dom'

class Router extends Component {
  constructor (props) {
    super(props)
    
  } 

  render () {
    return (
      <Router>
        // 每个路由配置都是一个Route
        <Route exact path="/" component={}></Route>
        // 嵌套路由有两种方式 1 使用render和父路由写在一起,需要给子组件中添加this.props.children
        <Route render={() => (
          <组件>
            <Route path="" componet={}></Route>
          </组件>
        )}></Route>

        // 2 把子路由写在对应的组件中

        <Route exact path="/" component={Child}></Route>

      </Router>
    )
  }
}

Child.js

import React, { Component } from 'react'
import { Route } from 'react-router-dom'

class Router extends Component {
  constructor (props) {
    super(props)
    
  } 

  render () {
    return (
      <div>
        <Route path="" component={}></Route>
        <Route path="" component={}></Route>
        <Route path="" component={}></Route>
        <Route path="" component={}></Route>
      </div>
    )
  }
}

参数接收

params 动态路由
<Route to="/demo/:id"></Route>

this.props.match.params.id // 刷新页面不会消失
query

需要借助Link进行页面的跳转

<Link to={{pathname: '/demo', query: {id: 1}}}></Link>

this.props.location.query.id // 刷新页面后数据消失
state

需要借助Link进行页面的跳转

<Link to={{pathname: '/demo', state: {id: 1}}}></Link>

this.props.location.state.id // 刷新页面后数据不会消失
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值