1. 程式人生 > 其它 >React使用useLocation監聽url地址變化,工具URLSearchParams獲取引數

React使用useLocation監聽url地址變化,工具URLSearchParams獲取引數

import * as React from 'react'
import { Link, useLocation } from 'react-router-dom'
export interface BottomNavigationViewProps {
  className?: string
  isLogin?: boolean
  avatar?: string
  userMenuOpen?: boolean
  hasNotification?: boolean
  onUserMenuOpen?: () => void
  onUserMenuClose?: UserMenuProps['onUserMenuClose']
  onLoginClick
?: (event: React.MouseEvent<HTMLButtonElement>) => void } const NAVIGATION_ITEMS = [ { id: 'home', icon: 'home', href: '/', path: /^\/$/, name: '首頁', }, { id: 'discuss', icon: 'discuss', href: '/discussion', path: /^\/discussion/, name: '討論', }, // { //
id: 'purchased', // icon: 'myShow', // href: '/purchased', // path: /^\/purchased/, // name: '我的專案', // }, ] /** * 一個底欄導航元件,僅在移動端展示。某種 Material Design 原教旨主義玩家公敵。 * @param props 向元件內部傳入的引數。 * @param props.className (可選)為本元件額外追加的 class 名稱。 */ const BottomNavigationView: React.FC<BottomNavigationViewProps> = ({ className, isLogin, avatar, userMenuOpen, onUserMenuOpen, onUserMenuClose, onLoginClick, hasNotification, ...props })
=> { const mainClassName = cn(styles.bottomNavigation, className) const location = useLocation() const utm = new URLSearchParams(location.search) if (utm.get("utm_source")) { localStorage.setItem("utm_source",utm.get("utm_source")||"") } return ( <> <i className={styles.placeHolder} /> <div className={mainClassName}> <nav className={styles.nav}> {NAVIGATION_ITEMS.map((navigationItem) => ( <li key={navigationItem.id} className={cn({ [styles.current]: location.pathname.match(navigationItem.path), })} > <Link className={styles.link} to={navigationItem.href}> <span className={styles.iconContainer}> <Icon name={navigationItem.icon} /> </span> <span className={styles.label}>{navigationItem.name}</span> </Link> </li> ))} <li className={cn({ [styles.current]: location.pathname.match(/\/(settings|member)$/), })} > {isLogin ? ( <div className={cn(styles.link, styles.withUserMenu)}> <Button className={cn( styles.userMenuLinkContainer, styles.buttonLink )} color="content" onClick={() => onUserMenuOpen && onUserMenuOpen()} > <RedDot show={hasNotification}> <span className={styles.iconContainer}> <Avatar alt="您的頭像" src={avatar} size="w20" /> </span> </RedDot> <span className={styles.label}>我的</span> </Button> <div className={styles.userMenuContainer}> <UserMenu showUserRightButton className={styles.userMenu} open={userMenuOpen} corner="bottom" hasNotification={hasNotification} onUserMenuClose={() => onUserMenuClose && onUserMenuClose()} /> </div> </div> ) : ( <Button className={cn(styles.link, styles.buttonLink)} color="content" onClick={onLoginClick} > <span className={styles.iconContainer}> <Icon name="userCenter" /> </span> <span className={styles.label}>我的</span> </Button> )} </li> </nav> </div> </> ) } export default React.memo(BottomNavigationView)