您现在的位置是:首页 >技术教程 >【react】react18的学习(九)–路由react-router-dom@5网站首页技术教程

【react】react18的学习(九)–路由react-router-dom@5

ANKG 2024-08-11 12:01:02
简介【react】react18的学习(九)–路由react-router-dom@5

常用标签:

  • BrowserRouter:history模式
  • HashRouter:哈希模式;
  • Link:路由跳转标签;参数:to(跳转的路由地址)、
  • Route:渲染路由页面标签;参数:exact(精准匹配)、path(路由地址)、component(渲染的组件)
  • Redirect:重定向标签;
  • Switch:确保每次只匹配一个路由页面;
  • Suspense:懒加载标签

路由配置:

import React, { lazy, Suspense } from 'react'
import { BrowserRouter, HashRouter, Link, Route, Redirect, Switch } from 'react-router-dom'
import A from './router5-demo/A'

const App = () => {
  return (
    <HashRouter>
      <div>
        <Link to="/a">a</Link>
        <Link to="/b">b</Link>
        <Link to="/c">c</Link>
      </div>
      <div>
        <Suspense fallback={<>正在加载中...</>}>
          <Switch>
            <Route exact path="/" component={A}></Route>
            <Route
              path="/b"
              component={lazy(() => import('./router5-demo/B'))}
            ></Route>
            <Route
              path="/c"
              component={lazy(() => import('./router5-demo/C'))}
            ></Route>
            <Redirect to="/"></Redirect>
          </Switch>
        </Suspense>
      </div>
    </HashRouter>
  )
}

路由对象获取:

  • hooks函数:给路由模块中所有组件提供路由对象(history, location, match)
  • props:只给路由模块里面的路由组件提供路由对象;
  • 所以针对不是路由组件的类组件想使用路由对象:高阶组件HOC、withRouter组件
// 路由组件获取路由对象:props、hooks函数(针对函数组件)、this.props(针对类组件)
import React from 'react'
import { useHistory, useLocation, useRouteMatch } from 'react-router-dom'

const A = props => {
  console.log(useHistory())
  console.log(props);
  let { history, location, match } = props
  return <div>a组件</div>
}

export default A
// 非路由组件获取路由对象:hooks函数(针对函数组件)、高阶组件(针对类组件:用函数组件包住类组件)
import React, { Component } from 'react'
import { useHistory, useLocation, useRouteMatch } from 'react-router-dom'
class A extends Component {
  render() {
    console.log(this.props)
    return ();
  }
}
const ProxyCom = function (Component) {
  return function HOC(props) {
  	let history = useHistory()
    return <Component {...props} history={history}></Component>
  }
}
export default ProxyCom(A)
// 使用react-router-dom@5 自带的函数withRouter:就是封装的HOC
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
class A extends Component {
  render() {
    console.log(this.props)
    return ();
  }
}
export default withRouter(A)

路由跳转:

  • Link标签:声明式导航;与下方传参基本一样
<Link to="/">a</Link>
  • 路由对象的history:编程式导航;
<button onClick={() => {history.push('/c/10/zak')}}>跳转c</button>

路由传参:三种:query传参、路径传参、隐式传参(刷新参数会丢失)

  • query传参
// 传参
history.push('/c?id=10')
history.push({ pathname: '/c', search: qs.stringify({id:10}) }) //search必须是字符串
// 获取参数:路由对象
import qs from 'qs'
let { location } = props
let data = location.search //?id=10
let data = qs.parse(location.search.slice(1)) //{id:10}
let usp = new URLSearchParams(location.search)
console.log(usp.get('id'))// 10
  • 路径传参
// 路径参数,类似vue的params
<Route path="/c/:id?/:name?" component={lazy(() => import('./router5-demo/C'))}></Route>
// 传参
history.push('/c/10/zak')
// 获取参数:路由对象、useParams
let { match } = props
let params = match.params //{id: '10', name: 'zak'}
import { useParams } from 'react-router-dom'
let params = useParams()
  • 隐式传参(刷新参数会丢失)
// 传参
history.push({pathname: '/c',state: { id: 66 },})
// 获取参数
let { location } = props
let state = location.state //{id: 66}

NavLink标签与Link标签:

语法基本一样;

  • NavLink:更常用,给匹配的标签添加类active,可修改默认类名;
<NavLink to="/c" activeClassName="aa">c</NavLink>
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。