目前正在学习react router
,了解到v5和v6版本具有较大差异。本文将结合源代码详细说明react router v6
中发生改变的以及新增的hooks
通过阅读本篇文章,你将了解:
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;
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
中
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.
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。
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
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
的是何种操作
declare function useOutlet(): React.ReactElement | null;
返回路由当前路由的子路由的元素。这个hook
被Outlet
组件在内部使用用于渲染子路由。
Returns the element for the child route at this level of the route hierarchy. This hook is used internally by to render child routes.
declare function useParams<
K extends string = string
>(): Readonly<Params<K>>;
useParams
返回URL参数的键/值对的对象。使用它来访问当前Route
的match.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.
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的第二个参数的类型相同
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.
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 官方文档