React Router

目录

一、介绍

1、作用

2、安装

二、使用

1、导入

2、定义路由

2.1、HashRouter

2.2、Route

2.3、Switch

3、重定向

4、嵌套路由

5、路由传参

5.1、使用params参数

5.2、使用search参数

5.3、使用state参数

6、声明式路由导航和编程式路由导航

6.1、声明式路由导航

6.2、编程式路由导航

7、withRouter

7.1、作用

7.2、使用方法


一、介绍

1、作用

路由是根据不同的URL地址展示不同的页面或者内容

2、安装

npm install react-router-dom@5

二、使用

1、导入

//引入
import   {HashRouter,  Route,  Switch}  from  'react-router-dom'

2、定义路由

建议:将路由单独封装在一个js文件中

注意:一级路由与多级路由

render(){
     return  (
       <div>
          <HashRouter>
             <Switch>
                <Route path="/about" component={About} />
                <Route path="/home" component={Home} />
                <Redirect to='/about' />
             </Switch>
          </HashRouter>
       </div>
     )
}

2.1、HashRouter

作用:包裹整个应用,一个React应用只使用一次

HashRouter与BrowserRouter的比较:

模式URL表现形式刷新后对路由state参数的影响
HashRouterlocalhost:3000/#刷新后会导致路由state参数的丢失

BrowserRouter

localhost:3000/没有任何影响,state保存在history对象中

2.2、Route

作用:用于定义路由路径和渲染组件的对应关系

2.3、Switch

使用Switch包裹Route来实现单一匹配,即匹配到一个路径之后,就会停止向下匹配,若不使用Switch包裹,则继续向下匹配

3、重定向

3.1、作用

如果我们不想让用户访问某个路由或者该路由不在我们书写的路由中,我们可以让组件跳转到我们指定的路由

 <Redirect  to='/home/hot' />

4、嵌套路由

//父组件   
<HashRouter>
   <div>
     <NavLink to="/about">组件About</NavLink> <span></span>
     <NavLink to="/home">组件Home</NavLink>
     <Switch>
        <Route path="/about" component={About} />
        <Route path="/home" component={Home} />
        <Redirect to='/about' />
      </Switch>
    </div>
</HashRouter>

//子组件
<div>
  <h3>Home内容</h3>
  <NavLink to='/home/hot'>二级hot</NavLink> <span></span>
  <NavLink to='/home/message'>二级message</NavLink>
  <div>
    <Switch>
      <Route path='/home/hot' component={Hot} />
      <Route path='/home/message' component={Message} />
      <Redirect to='/home/hot' />
    </Switch>
  </div>
</div>

5、路由传参

5.1、使用params参数

1、传递params参数:<Link  to='/demo/test/001/aa'>展示</Link>
2、声明接收params参数:<Route  path='/demo/test/:id/:title'   component='{Test}'   />
3、接收params参数:const   {id, title} = props.match.params

const index = () => {
 const arr = [
      {id:'001',title:'one'},
      {id:'002',title:'two'},
      {id:'003',title:'three'},
    ]
  return (
    <div>
      <ul>
        {
          arr.map((msg) => (
            <li key={msg.id}>
              {/* 向路由组件传递params参数 */}
              <Link to={`/home/message/detail/${msg.id}/${msg.title}`}>{msg.title}</Link>
            </li>
          ))
        }
      </ul>
      <hr />
      {/* 声明接收params参数 */}
      <Route path='/home/message/detail/:id/:title' component={Detail} />
    </div>
  )
}


const index = (props) => {
    const data = [
        {id:'001',text:'第一名'},
        {id:'002',text:'第二名'},
        {id:'003',text:'第三名'},
    ]
    //接收params参数
    const {id, title} = props.match.params
    const SearchResult = data.find((dataobj) => {
        return dataobj.id === id;
    })
  return (
    <div>
        <ul>
            <li>id:{id}</li>
            <li>title:{title}</li>
            <li>nm:{SearchResult.text}</li>
        </ul>

    </div>
  )
}

5.2、使用search参数

1、传递参数:<Link  to='/demo/test?id=001&title=aa'>展示</Link>

2、不用声明接收:<Route  path='/demo/test'  component='{Test}'   />

3、接收search参数:接收到的数据为字符串形式,需要转换成对象

const index = () => {
 const arr = [
      {id:'001',title:'one'},
      {id:'002',title:'two'},
      {id:'003',title:'three'},
    ]
  return (
    <div>
      <ul>
        {
          arr.map((msg) => (
            <li key={msg.id}>
              {/* 向路由组件传递search参数 */}
              <Link to={`/home/message/detail/?id=${msg.id}&title=${msg.title}`}> {msg.title}</Link>
            </li>
          ))
        }
      </ul>
      <hr />
      <Route path='/home/message/detail' component={Detail} />
    </div>
  )
}


const index = (props) => {
    const detaildata = [
        {id:'001',text:'第一名'},
        {id:'002',text:'第二名'},
        {id:'003',text:'第三名'},
    ]
    //接收search参数
    const {search} = props.location
    const querystring = require('querystringify')
    const obj = querystring.parse(search.slice(1)) 
    const {id, title} = obj   

    const SearchResult = detaildata.find((dataobj) => {
        return dataobj.id === id;
    })
  return (
    <div>
      <ul>
        <li>id:{id}</li>
        <li>title:{title}</li>
        <li>nm:{SearchResult.text}</li>
      </ul>
    </div>
  )
}

5.3、使用state参数

1、传递state参数:<Link  to={{pathname:'/home/message/detail', state:{id:'001',title:'aa'}}}>展示</Link>
2、不用声明接收:<Route  path='/demo/test/'  component='{Test}'   />
3、接收state参数:const  {id, title} = props.location.state

注意:刷新后对路由state参数的影响

             (1)、BrowserRouter没有任何影响,因为state保存在history对象中。

             (2)、HashRouter刷新后会导致路由state参数的丢失

const index = () => {
 const arr = [
      {id:'001',title:'one'},
      {id:'002',title:'two'},
      {id:'003',title:'three'},
    ]
  return (
    <div>
      <ul>
        {
          arr.map((msg) => (
            <li key={msg.id}>
              {/* 向路由组件传递state参数 */}
              <Link to={{pathname:'/home/message/detail',state:{id:msg.id,title:msg.title}}}>{msg.title}</Link>
            </li>
          ))
        }
      </ul>
      <hr />
      <Route path='/home/message/detail' component={Detail} />
    </div>
  )
}

const index = (props) => {
    const detaildata = [
        {id:'001',text:'第一名'},
        {id:'002',text:'第二名'},
        {id:'003',text:'第三名'},
    ]
    
    //接收state参数
    const {id, title} = props.location.state || {}

    const SearchResult = detaildata.find((dataobj) => {
        return dataobj.id === id;
    }) || {}
  return (
    <div>
        <ul>
            <li>id:{id}</li>
            <li>title:{title}</li>
            <li>nm:{SearchResult.text}</li>
        </ul>
    </div>
  )
}

6、声明式路由导航和编程式路由导航

6.1、声明式路由导航

<NavLink  to="/home">home</NavLink>
<NavLink  to="/second">second</NavLink>
<NavLink  to="/mine">mine</NavLink>

6.2、编程式路由导航

利用props.history对象下的push和replace进行跳转

1、push(跳转会形成history,可返回到上一层)

props.history.push('/home/message/detail/${id}/${title}')

2、replace(replace跳转不会形成history,不可以返回到上一层, 适用于登录后,不需要重新回到登录页面)

props.history.replace('/home/message/detail/${id}/${title}')

7、withRouter

7.1、作用

可以让一般组件(没有通过component渲染的组件)获取到history属性

7.2、使用方法

1、在需要使用history属性的组件中引入withRouter

import {withRouter} from 'react-router-dom'

2、默认导出

export default withRouter(组件名称)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值