示例
react-router-dom 6.30.4: useNavigate
已验证示例 — npm react-router-dom 6.30.4: useNavigate. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: useNavigate throws invariant error when invoked…
sha256:335af718e8972e828bfbbbaa334943c700ca3eee38edc3853b62cc860d32604d
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-25 |
案例
HOW- 目标
- verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4
- 符号
-
- react-router-dom.useNavigate
- 环境
- node 22.23.2
- 创建时间
- 2026-08-25T12:33:56Z
契约
- useNavigate throws invariant error when invoked outside of a Router context.
- useNavigate returns a callable navigation function when rendered within a Router provider.
- navigate performs push navigation updating the current pathname location and route matches.
- navigate supports replace option to replace current history entry instead of pushing a new entry.
- navigate passes state object accessible via location.state in target route.
- navigate performs delta navigation with negative and positive numbers to traverse history entries.
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.js
源代码
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/react-router-dom@6.30.4
Demonstrate these symbols/APIs:
- react-router-dom.useNavigate
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:5d8fbf01f11534c3d7c950c5e626e2b8431ef83e89faa84a4cb1301586a3f36a","constraints":{"executionContext":"node"},"contract":["useNavigate throws invariant error when invoked outside of a Router context.","useNavigate returns a callable navigation function when rendered within a Router provider.","navigate performs push navigation updating the current pathname location and route matches.","navigate supports replace option to replace current history entry instead of pushing a new entry.","navigate passes state object accessible via location.state in target route.","navigate performs delta navigation with negative and positive numbers to traverse history entries."],"goal":"verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4","kind":"HOW","packages":["pkg:npm/react-router-dom@6.30.4"],"schemaVersion":1,"symbols":["react-router-dom.useNavigate"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react-router-dom@6.30.4"],"schemaVersion":1,"subject":"pkg:npm/react-router-dom@6.30.4","symbols":["react-router-dom.useNavigate"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-react-router-dom-use-navigate",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-react-router-dom-use-navigate",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "6.30.4"
}
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
},
"peerDependencies": {
"react": "^18.3.1"
}
},
"node_modules/react-router": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8"
}
},
"node_modules/react-router-dom": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3",
"react-router": "6.30.4"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
}
}
}
{
"name": "sample-react-router-dom-use-navigate",
"version": "1.0.0",
"private": true,
"license": "MIT-0",
"dependencies": {
"react": "18.3.1",
"react-dom": "18.3.1",
"react-router-dom": "6.30.4"
}
}
{
"schemaVersion": 1,
"goal": "verify react-router-dom.useNavigate in pkg:npm/react-router-dom@6.30.4",
"kind": "HOW",
"packages": [
"pkg:npm/react-router-dom@6.30.4"
],
"symbols": [
"react-router-dom.useNavigate"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const {
useNavigate,
useLocation,
createMemoryRouter,
MemoryRouter,
Routes,
Route,
} = require('react-router-dom');
const { StaticRouter } = require('react-router-dom/server');
/**
* Component that captures navigate and location hooks for inspection.
*/
function NavigationProbe({ onInspect }) {
const navigate = useNavigate();
const location = useLocation();
if (onInspect) {
onInspect({ navigate, location });
}
return React.createElement(
'div',
{ 'data-pathname': location.pathname, 'data-search': location.search },
`Current: ${location.pathname}`
);
}
/**
* Component that uses useNavigate for programmatic redirection / button triggers.
*/
function NavigatingComponent({ to, options }) {
const navigate = useNavigate();
return React.createElement(
'button',
{
type: 'button',
onClick: () => navigate(to, options),
},
'Go'
);
}
/**
* Renders a probe component inside MemoryRouter with specified initial entries.
*
* @param {string[]} initialEntries
* @param {number} [initialIndex=0]
* @param {Function} [onInspect]
* @returns {string} Rendered HTML string.
*/
function renderWithMemoryRouter(initialEntries = ['/'], initialIndex = 0, onInspect) {
const element = React.createElement(
MemoryRouter,
{ initialEntries, initialIndex },
React.createElement(NavigationProbe, { onInspect })
);
return ReactDOMServer.renderToStaticMarkup(element);
}
/**
* Renders a probe component inside StaticRouter.
*
* @param {string} location
* @param {Function} [onInspect]
* @returns {string} Rendered HTML string.
*/
function renderWithStaticRouter(location, onInspect) {
const element = React.createElement(
StaticRouter,
{ location },
React.createElement(NavigationProbe, { onInspect })
);
return ReactDOMServer.renderToStaticMarkup(element);
}
/**
* Attempts to render a component using useNavigate without an enclosing Router.
* Throws an invariant error.
*/
function renderWithoutRouter() {
function Standalone() {
useNavigate();
return null;
}
return ReactDOMServer.renderToStaticMarkup(React.createElement(Standalone));
}
/**
* Creates an in-memory data router supporting full imperative navigation.
*
* @param {Array} routes
* @param {Object} [options]
* @returns {Object} Router instance
*/
function createNavigationRouter(routes, options = {}) {
return createMemoryRouter(routes, {
initialEntries: options.initialEntries || ['/'],
initialIndex: options.initialIndex !== undefined ? options.initialIndex : 0,
});
}
/**
* Performs push navigation on a router instance.
*
* @param {Object} router
* @param {string|Object} to
* @param {Object} [options]
*/
function navigateTo(router, to, options) {
router.navigate(to, options);
}
/**
* Performs delta navigation (back / forward) on a router instance.
*
* @param {Object} router
* @param {number} delta
*/
function navigateDelta(router, delta) {
router.navigate(delta);
}
module.exports = {
useNavigate,
NavigationProbe,
NavigatingComponent,
renderWithMemoryRouter,
renderWithStaticRouter,
renderWithoutRouter,
createNavigationRouter,
navigateTo,
navigateDelta,
};
const assert = require('node:assert/strict');
const {
useNavigate,
NavigationProbe,
NavigatingComponent,
renderWithMemoryRouter,
renderWithStaticRouter,
renderWithoutRouter,
createNavigationRouter,
navigateTo,
navigateDelta,
} = require('../src/index.js');
// 1. useNavigate throws invariant error when invoked outside of a Router context.
assert.throws(
() => {
renderWithoutRouter();
},
(err) => {
return (
err instanceof Error &&
/useNavigate\(\) may be used only in the context of a <Router> component/.test(err.message)
);
},
'useNavigate rendered outside Router must throw an invariant error'
);
// 2. useNavigate returns a callable navigation function when rendered within a Router provider.
{
let inspectedMemory = null;
const memoryMarkup = renderWithMemoryRouter(
['/dashboard?tab=overview#stats'],
0,
(ctx) => {
inspectedMemory = ctx;
}
);
assert.ok(memoryMarkup.includes('Current: /dashboard'), 'MemoryRouter must render probe markup');
assert.ok(inspectedMemory !== null, 'Probe must capture context inside MemoryRouter');
assert.strictEqual(typeof inspectedMemory.navigate, 'function', 'useNavigate must return a function');
assert.strictEqual(inspectedMemory.location.pathname, '/dashboard');
assert.strictEqual(inspectedMemory.location.search, '?tab=overview');
assert.strictEqual(inspectedMemory.location.hash, '#stats');
let inspectedStatic = null;
const staticMarkup = renderWithStaticRouter('/profile/settings', (ctx) => {
inspectedStatic = ctx;
});
assert.ok(staticMarkup.includes('Current: /profile/settings'), 'StaticRouter must render probe markup');
assert.ok(inspectedStatic !== null, 'Probe must capture context inside StaticRouter');
assert.strictEqual(typeof inspectedStatic.navigate, 'function', 'useNavigate must return a function in StaticRouter');
assert.strictEqual(inspectedStatic.location.pathname, '/profile/settings');
}
// Router configuration for behavioral tests
const routeDefinitions = [
{
path: '/',
id: 'root',
children: [
{
index: true,
id: 'home',
},
{
path: 'users/:userId',
id: 'user-detail',
},
{
path: 'settings',
id: 'settings',
},
{
path: 'analytics',
id: 'analytics',
},
],
},
];
// 3. navigate performs push navigation updating the current pathname location and route matches.
{
const router = createNavigationRouter(routeDefinitions, {
initialEntries: ['/'],
initialIndex: 0,
});
assert.strictEqual(router.state.location.pathname, '/');
assert.strictEqual(router.state.matches[0].route.id, 'root');
navigateTo(router, '/users/alice');
assert.strictEqual(router.state.location.pathname, '/users/alice');
assert.strictEqual(router.state.matches.length, 2);
assert.strictEqual(router.state.matches[1].route.id, 'user-detail');
assert.strictEqual(router.state.matches[1].params.userId, 'alice');
}
// 4. navigate supports replace option to replace current history entry instead of pushing a new entry.
{
const router = createNavigationRouter(routeDefinitions, {
initialEntries: ['/', '/settings'],
initialIndex: 1,
});
assert.strictEqual(router.state.location.pathname, '/settings');
const previousHistoryIndex = router.state.historyIndex;
// Replace /settings with /analytics
navigateTo(router, '/analytics', { replace: true });
assert.strictEqual(router.state.location.pathname, '/analytics');
assert.strictEqual(router.state.historyIndex, previousHistoryIndex, 'Replace navigation must maintain current history index');
}
// 5. navigate passes state object accessible via location.state in target route.
{
const router = createNavigationRouter(routeDefinitions, {
initialEntries: ['/'],
initialIndex: 0,
});
const navigationPayload = { fromCheckout: true, orderId: 98765 };
navigateTo(router, { pathname: '/users/bob', search: '?view=orders' }, { state: navigationPayload });
assert.strictEqual(router.state.location.pathname, '/users/bob');
assert.strictEqual(router.state.location.search, '?view=orders');
assert.deepStrictEqual(router.state.location.state, navigationPayload, 'location.state must match navigated payload');
}
// 6. navigate performs delta navigation with negative and positive numbers to traverse history entries.
{
const router = createNavigationRouter(routeDefinitions, {
initialEntries: ['/', '/settings', '/analytics'],
initialIndex: 2,
});
assert.strictEqual(router.state.location.pathname, '/analytics');
// Navigate back 1 step
navigateDelta(router, -1);
assert.strictEqual(router.state.location.pathname, '/settings');
// Navigate back 1 more step
navigateDelta(router, -1);
assert.strictEqual(router.state.location.pathname, '/');
// Navigate forward 2 steps
navigateDelta(router, 2);
assert.strictEqual(router.state.location.pathname, '/analytics');
}
console.log('All react-router-dom.useNavigate contract tests passed successfully.');
原始种子者
匿名