React 学习笔记 - react router v6 hooks

前言

目前正在学习react router,了解到v5和v6版本具有较大差异。本文将结合源代码详细说明react router v6中发生改变的以及新增的hooks

通过阅读本篇文章,你将了解:

  • useHref
  • useInRouterContext
  • useLocation
  • useMatch
  • useNavigate
  • useNavigationType
  • useOutlet
  • useParams
  • useSearchParams
  • useResolvedPath
  • useRoutes

详解

useHref

declare function useHref(to: To): string;

功能

useHref钩子返回一个URL,可以用来链接到给定的to位置,甚至在React router之外。

The useHref hook returns a URL that may be used to link to the given to location, even outside of React Router.

useHref传入一个字符串或To对象,返回一个URL的绝对路径。可以在参数中传入一个相对路径、绝对路径、To对象。
react hooks v6中的Link组件内部使用useHref获取它的href值

export interface Path {
    
    
  pathname: Pathname;
  search: Search;
  hash: Hash;
}
export type To = string | Partial<Path>;

示例

当前路由:/page1/page2

import React, {
    
    useEffect} from 'react';
import {
    
    useHref} from 'react-router-dom';

function Page2(props) {
    
    
    useEffect(()=>{
    
    
        console.log(useHref('../')) // 输出 '/page1/'
      	console.log(useHref('../../')) // 输出 '/'
        console.log(useHref('/page1')) // 输出 '/page'
        console.log(useHref('/pageabc')) // 输出 '/pageabc' 可见路径与当前路由无关
        console.log(useHref({
    
    pathname:'/page1',search:'name=123',hash:'test'})) // 输出 '/page1?name=123#test'
    },[])
    return (
        <div></div>
    );
}

export default Page2;

useInRouterContext

declare function useInRouterContext(): boolean;

功能

如果组件在Router组件中的上下文中渲染,useInRouterContext将返回true,否则返回false。这对于一些需要知道是否在react router的上下文中渲染的第三方扩展非常有用。

The useInRouterContext hooks returns true if the component is being rendered in the context of a , false otherwise. This can be useful for some 3rd-party extensions that need to know if they are being rendered in the context of a React Router app.

判断当前组件是否在由Router组件创建的Context

useLocation

declare function useLocation(): Location;

interface Location extends Path {
    
    
  state: unknown;
  key: Key;
}

功能

这个hook返回当前路由的location对象。

This hook returns the current location object. This can be useful if you’d like to perform some side effect whenever the current location changes.

useMatch

declare function useMatch<ParamKey extends string = string>(
  pattern: PathPattern | string
): PathMatch<ParamKey> | null;

功能

返回给定路径上相对于当前位置的路由的匹配数据。

Returns match data about a route at the given path relative to the current location.

react router v5中的useRouteMatch在v6版本中更名为useMatch。内部示例调用了matchPath方法根据URL路径名匹配路由路径模式,并返回有关匹配的信息。如果模式与给定路径名不匹配,则返回null。

useNavigate

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
    
    
  (
    to: To,
    options?: {
    
     replace?: boolean; state?: any }
  ): void;
  (delta: number): void;
}

功能

useNavigate钩子返回一个函数,该函数允许您以编程方式进行导航,例如在提交表单之后。

The useNavigate hook returns a function that lets you navigate programmatically, for example after a form is submitted.

react router v5中组件获取到的useHistory在v6版本更名为useNavigate。在用法上作出了较大改变

示例

当前路由:/user/page2
其他路由:/user/page1

import React, {
    
    useEffect} from 'react'
import {
    
    useNavigate} from 'react-router-dom'

function Page2(){
    
    
  let navigate = useNavigate()
  useEffect(()=>{
    
    
  	navigate('/user/page1') // 导航到'/user/page1'
    navigate('../') // 导航到'/user'
    navigate(-1) // 导航到/user/page1 相当于v5中history.go(-1) history.goBack()
    navigate(1) //导航到/user 相当于v5中history.go(1) history.goForward()
    navigate('/user/page2/',{
    
    replace:true,state:{
    
    name:123}} // 相当于v5中history.replace(),并同时传入state
  },[])
  return <div></div>
}

export default Page2

useNavigationType

declare function useNavigationType(): NavigationType;
type NavigationType = "POP" | "PUSH" | "REPLACE";

功能

这个钩子返回当前的导航类型或用户如何到达当前页面;通过历史堆栈上的pop、push或replace操作。

This hook returns the current type of navigation or how the user came to the current page; either via a pop, push, or replace action on the history stack.

这个hooks类似react router v5中组件传入参数中的history对象的action属性,返回触发当前navigate的是何种操作

useOutlet

declare function useOutlet(): React.ReactElement | null;

功能

返回路由当前路由的子路由的元素。这个hookOutlet组件在内部使用用于渲染子路由。

Returns the element for the child route at this level of the route hierarchy. This hook is used internally by to render child routes.

useParams

declare function useParams<
  K extends string = string
>(): Readonly<Params<K>>;

功能

useParams返回URL参数的键/值对的对象。使用它来访问当前Routematch.params。子路由从其父路由继承所有参数。

The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the . Child routes inherit all params from their parent routes.

useSearchParams

declare function useSearchParams(
  defaultInit?: URLSearchParamsInit
): [URLSearchParams, SetURLSearchParams];

type ParamKeyValuePair = [string, string];

type URLSearchParamsInit =
  | string
  | ParamKeyValuePair[]
  | Record<string, string | string[]>
  | URLSearchParams;

type SetURLSearchParams = (
  nextInit?: URLSearchParamsInit,
  navigateOpts?: : {
    
     replace?: boolean; state?: any }
) => void;

功能

useSearchParams用于读取和修改URL中当前位置的查询字符串。与useState一样,useSearchParams返回一个包含两个值的数组:当前位置的搜索参数一个可用于更新它们的函数

The useSearchParams hook is used to read and modify the query string in the URL for the current location. Like React’s own useStatehook, useSearchParams returns an array of two values: the current location’s search params and a function that may be used to update them.

useSearchParams的工作原理与navigate类似,但仅适用于URL的search部分。

注意:setSearchParams的第二个参数要与navigate的第二个参数的类型相同

useResolvedPath

declare function useResolvedPath(to: To): Path;

功能

这个hook解析给定to对象中的pathname与当前位置的路径名,并返回一个Path对象

This hook resolves the pathname of the location in the given to value against the pathname of the current location.

useRoutes

declare function useRoutes(
  routes: RouteObject[],
  location?: Partial<Location> | string;
): React.ReactElement | null;

功能

useRoutes钩子与Route组件是功能相等的,但它使用JavaScript对象而不是Route元素取定义你的路由。该对象与Route元素具有相同的属性,但是它们不需要JSX

The useRoutes hook is the functional equivalent of , but it uses JavaScript objects instead of elements to define your routes. These objects have the same properties as normal elements, but they don’t require JSX.

注意:useRoutes的返回值要么是一个可以让你用于渲染路由树的React Element,要么是null(路由不匹配时)

参考文档

remix-run/react-router/packages/react-router/index.tsx
remix-run/react-router/packages/react-router-dom/index.tsx
remix-run/history/packages/history/index.ts
react router 官方文档

猜你喜欢

转载自blog.csdn.net/m0_52761633/article/details/123878885