一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情。
大家好,我是大帅子,今天给大家讲一下react中的路由,前面我也给大家讲了一下路由,因为今天有一个新的知识点,今天就带着大家再把路由过一下,下面我们直接开始吧
1. 基本用法
以下的三种写法都可以的,看个人习惯
1. 第一种写法
<Router exact path='/' render={()=><Redireact to='/home' />}>
<Router>
2. 第二种写法
<Route exact path='/home'>
<Home>
</Route>
2. 第三种写法
<Route exact path='/home' component={}>
<Home>
</Route>
2.KeepAlive
这个组件是为了 点击页面跳转之后,还保持当前的页面的位置
1. 先创建组件
我们这边最好把这个组件建在component里面,
components/Keepalive/Keepalive.tsx
/* eslint-disable react/no-children-prop */
import React from 'react'
import { Route, RouteChildrenProps, RouteProps } from 'react-router'
type Props = RouteProps
export default function KeepAlive ({ path, children, ...rest }: Props) {
const child = (props: RouteChildrenProps) => {
console.log('child....', props)
// const isMatch = props.location.pathname.startsWith(path as string)
return (
<div
className="keep-alive"
style={{ display: props.match ? 'block' : 'none' }}>
{children}
</div>
)
}
// 路径 小功能 组件
return <Route path={path} {...rest} children={child} />
}
2. 我们找到需要进行活着的组件,在外面包一层
<KeepAlive path=home exact>
<Home />
<KeepAlive>
3.路由传参
- state
history.push('/xx' , {from:xxxx})
- 动态路由
<route path='/xxx/:id'>
props.match.params
- 查询字符串 (主要用来查询的时候)
history.push(/xxx?a=123&b=222)
new URLSearchParams(location.search).get('要拿的值')
这边我为了方便大家理解,写了这个图,在不同的时候,我们要用到的路由传参是不一样的,大家依据情况判断哦
好了,这边已经给大家介绍到这里,以上是我自己的理解,希望可以帮到大家, 欢迎留言我这边一定会第一时间给大家解答,喜欢的可以点赞收藏
🐣---->🦅 还需努力!大家一起进步!!!