useNavigatedeclare function useNavigate(): NavigateFunction;
interface NavigateFunction {
(to: To, options?: NavigateOptions): void;
(delta: number): void;
}
interface NavigateOptions {
replace?: boolean;
state?: any;
preventScrollReset?: boolean;
relative?: RelativeRoutingType;
unstable_flushSync?: boolean;
unstable_viewTransition?: boolean;
}
type RelativeRoutingType = "route" | "path";
redirect 中使用 loaders 和 actions,而不是这个钩子
useNavigate 钩子返回一个函数,允许您以编程方式导航,例如在效果中
import { useNavigate } from "react-router-dom";
function useLogoutTimer() {
const userIsInactive = useFakeInactiveUser();
const navigate = useNavigate();
useEffect(() => {
if (userIsInactive) {
fake.logout();
navigate("/session-timed-out");
}
}, [userIsInactive]);
}
navigate 函数有两个签名
To 值(与 <Link to> 相同类型),并带有一个可选的第二个 options 参数(类似于您可以传递给 <Link> 的 props),或者navigate(-1) 等同于点击后退按钮useResolvedPath 文档中的 Splat 路径 部分,了解有关 future.v7_relativeSplatPath 未来标志对 splat 路由中相对 useNavigate() 行为的影响的说明
options.replace指定 replace: true 将导致导航替换历史堆栈中的当前条目,而不是添加新的条目。
options.state您可以包含一个可选的 state 值以存储在 历史状态 中,然后您可以通过 useLocation 在目标路由上访问它。例如
navigate("/new-route", { state: { key: "value" } });
options.preventScrollReset当使用 <ScrollRestoration> 组件时,您可以通过 options.preventScrollReset 禁用将滚动重置到页面顶部。
options.relative默认情况下,导航相对于路由层次结构(relative: "route"),因此 .. 将向上移动一个 Route 层级。有时,您可能会发现您有匹配的 URL 模式,这些模式在嵌套方面没有意义,并且您希望使用相对路径路由。您可以使用 relative: "path" 选择这种行为
// Contact and EditContact do not share additional UI layout
<Route path="/" element={<Layout />}>
<Route path="contacts/:id" element={<Contact />} />
<Route
path="contacts/:id/edit"
element={<EditContact />}
/>
</Route>;
function EditContact() {
// Since Contact is not a parent of EditContact we need to go up one level
// in the path, instead of one level in the Route hierarchy
navigate("..", { relative: "path" });
}
请注意,relative: "path" 仅影响相对路径的解析。它不会更改该相对路径解析的“起始”位置。此解析始终相对于路由层次结构中的当前位置(即调用 useNavigate 的路由)。
如果您希望对当前 URL 而不是路由层次结构使用路径相对路由,您可以使用当前的 location 和 URL 构造函数(注意尾部斜杠的行为)
// Assume the current URL is https://remix.org.cn/docs/en/main/start/quickstart
let location = useLocation();
// Without trailing slashes
new URL(".", window.origin + location.pathname);
// 'https://remix.org.cn/docs/en/main/start/'
new URL("..", window.origin + location.pathname);
// 'https://remix.org.cn/docs/en/main/'
// With trailing slashes:
new URL(".", window.origin + location.pathname + "/");
// 'https://remix.org.cn/docs/en/main/start/quickstart/'
new URL("..", window.origin + location.pathname + "/");
// 'https://remix.org.cn/docs/en/main/start/'
options.unstable_flushSyncunstable_flushSync 选项告诉 React Router DOM 将此导航的初始状态更新包装在一个 ReactDOM.flushSync 调用中,而不是默认的 React.startTransition。这允许您在更新刷新到 DOM 后立即执行同步 DOM 操作。
unstable_flushSync 仅在使用数据路由器时有效,请参阅 选择路由器
options.unstable_viewTransitionunstable_viewTransition 选项通过将最终状态更新包装在 document.startViewTransition() 中,为此导航启用 视图转换。如果您需要为此视图转换应用特定样式,您还需要利用 unstable_useViewTransitionState()。
unstable_viewTransition 仅在使用数据路由器时有效,请参阅 选择路由器