React(博客系列二),路由传参的几种方式

4,251 阅读2分钟

1.params(动态路由)方式

地址栏可见,与拼接的地址不一样(不会有问号),刷新仍然存在

路由配置

<Route path='/home/:id' component={Home} />

跳转传参

 <NavLink className="right-link" to='/home/1' onClick={() => setActiveName({ name: '博客首页', path: "/home" })}>            <HomeOutlined /> 博客首页          </NavLink>

页面取值

props取值

props.match.params.id

使用hooks取值

简单介绍一下路由里面几个hooks的用法,以下是控制台打印出来的每个hooks

useHistory

useLocation

useParams

useRouterMatch

由上可以看出只有useParams、useRouterMatch两个hooks可以用来取params的值

通过react-router-dom里面的useParams取值

const param: Params = useParams()
console.log(param.id);

通过react-router-dom里面的useRouterMatch取值

const match: Params = useRouteMatch()console.log(match.param.id);

2.get(类似query)方式

地址栏可见,刷新仍然存在

路由配置

<Route path='/frame' component={Frame} />

跳转传参,不再支持query在路由对象里面传参的方式了(自测不成功),这里使用了拼接的方式(参考官网的)

<NavLink className="right-link" to='/frame?name=yydbb' onClick={() => setActiveName({ name: '前端框架', path: "/frame" })}>            <ShareAltOutlined /> 前端框架          </NavLink>

页面取值

props取值,打印一下props

可以看出我们的参数在location的saerch里面, 官方提供一种使用自定义hook(封装统一使用)获取这个参数

自定义hook

import { useLocation } from 'react-router-dom'export function useQuery() {  return new URLSearchParams(useLocation().search);}

页面使用

import { useQuery } from '../hooks/useQuery'
const query = useQuery()
const name = query.get('name')

现在我们试着用props取query,原理和上面一样,所以建议使用上面的方法

const nameParams = new URLSearchParams(props.location.search)console.log(nameParams.get('name'));

3.state方式

地址栏不可见,刷新不存在

路由配置

<Route path='/note' component={Note} />

跳转传参

<NavLink className="right-link" to={{pathname:'/note',state:{id:12}}} onClick={() => setActiveName({ name: '搭建笔记', path: "/note" })}>            <BarsOutlined /> 搭建笔记          </NavLink>

页面取值

props取值,这里的取值是有点麻烦的,涉及到类型定义,路由里面的state类型为unknown,所以我们使用了联合类型,自定义了一个type MLocation,解决了这个state的类型报错问题

import React from 'react';import { RouteComponentProps, useLocation, useHistory } from 'react-router-dom'type SLocation = {  state?: {    id: number  }}type MLocation<S> = {  location: S}type combineProps = RouteComponentProps & MLocation<SLocation>const Note: React.FC<combineProps> = (props) => {  console.log(props.location.state?.id);  const history: MLocation<SLocation> = useHistory()  console.log(history.location.state?.id);  const location: SLocation = useLocation()  console.log(location.state?.id);  return (    <div className="App">      {props.location.state?.id}    </div>  );}export default Note;

hooks取值

useHistory、useLocation

const history: MLocation = useHistory()console.log(history.location.state?.id);const location: SLocation = useLocation()console.log(location.state?.id);

结语

由于项目中用到react-router-dom,所以花了点时间粗略(不全)的了解了一下,做个小笔记