useResolvedPath
根据当前位置的路径名解析给定 to
值的 pathname
,并返回 Path
对象。
¥Resolves the pathname
of the given to
value against the pathname of the current location and returns a Path
object.
import { useResolvedPath } from "@remix-run/react";
function SomeComponent() {
const path = useResolvedPath("../some/where");
path.pathname;
path.search;
path.hash;
// ...
}
这在使用相对值构建链接并在 <NavLink>
内部使用时非常有用。
¥This is useful when building links from relative values and used internally for <NavLink>
.
¥Splat Paths
React Router 的 useResolvedPath
hook 的原始逻辑对于 splat 路径的行为有所不同,事后看来,这是不正确/有缺陷的行为。有关更详细的解释,请参阅 React Router 文档,但该问题被确定为 "重大错误修复",并在 React Router 中通过 Future 标志修复,并通过 Remix 中的 v3_relativeSplatPath
Future 标志公开。这将成为 Remix v3 中的默认行为,因此建议你在方便时更新你的应用,以便为最终的 v3 升级做好更好的准备。
¥The original logic for React Router's useResolvedPath
hook behaved differently for splat paths that in hindsight was incorrect/buggy behavior. Please see the React Router Docs for a longer explanation, but this was determined to be a "breaking bug fix" and was fixed behind a future flag in React Router and exposed up through a v3_relativeSplatPath
Future Flag in Remix. This will become the default behavior in Remix v3, so it is recommended to update your applications at your convenience to be better prepared for the eventual v3 upgrade.
需要注意的是,这是 Remix 中所有相对路由的基础,因此这也适用于以下相对路径代码流:
¥It should be noted that this is the foundation for all relative routing in Remix, so this applies to the following relative path code flows as well:
<Link to>
useNavigate()
useHref()
<Form action>
useSubmit()
加载器和操作返回的 redirect
响应的相对路径
¥Relative path redirect
responses returned from loaders and actions
¥Behavior without the flag
未启用此标志时,默认行为是在解析 splat 路由中的相对路径时,忽略路径的 splat 部分。所以,在 routes/dashboard.$.tsx
文件中,即使当前 URL 是 /dashboard/teams
,useResolvedPath(".")
也会解析为 /dashboard
。
¥When this flag is not enabled, the default behavior is that when resolving relative paths inside a splat route, the splat portion of the path is ignored. So, within a routes/dashboard.$.tsx
file, useResolvedPath(".")
would resolve to /dashboard
even if the current URL was /dashboard/teams
.
¥Behavior with the flag
启用此标志后,此 "bug" 将被修复,以便所有路由类型的路径解析保持一致,并且 useResolvedPath(".")
始终解析为上下文路由的当前路径名。这包括任何动态参数或 splat 参数值,因此在 routes/dashboard.$.tsx
文件中,当当前 URL 为 /dashboard/teams
时,useResolvedPath(".")
将解析为 /dashboard/teams
。
¥When you enable the flag, this "bug" is fixed so that path resolution is consistent across all route types, and useResolvedPath(".")
always resolves to the current pathname for the contextual route. This includes any dynamic param or splat param values, so within a routes/dashboard.$.tsx
file, useResolvedPath(".")
would resolve to /dashboard/teams
when the current URL was /dashboard/teams
.
¥Additional Resources