积分规则
- 在
flattenRoutes 中会拍平路由结构的过程中 , 会形成一个一个的branch , 而每一个branch会通过 computeScore得到一个score. 这个score会影响后续matchRouteBranch的匹配结果.
computeScore
- dynamicSegmentValue: 动态参数 记3分
<Route path="/user/:id" element={<Detail />}>
- indexRouteValue: 索引路由 记2分
<Route index element={<Home />} />
- emptySegmentValue: 空 segment 记1分
<Route path="/user/info/" element={<Detail />} />
- staticSegmentValue: 字符串 segment 记10分
<Route path="/user/info" element={<Detail />} />
<Route path="*" element={<NoMatch />} />
一个🌰
<Routes>
<Route index element={<Home />} />
<Route path="/" element={<About />} />
<Route path=":id" element={<Dashboard />} />
<Route path="*" element={<NoMatch />} />
</Routes>
- 第一个 2 对应两个
segments(这里得到的两个'')
- 第二个 2 对应
index
- 第三个 2 对应两个
emptySegmentValue
const score = 2 + 2 + 2
- 第二个
branch的得分同上, 不过少了 index 所以得分为 4
const score = 2 + 2
- 第一个 2 对应两个
segments(一个''和:id)
- 第二个 3 对应
dynamicSegmentValue
- 第三个 1 对应一个
emptySegmentValue
const score = 2 + 3 + 1
- 第一个 2 对应两个
segments(一个''和*)
- 第二个 -2 对应
*
- 第三个 1 对应 一个
emptySegmentValue
const score = 2 - 2 + 1
具体源码和注释
const paramRe = /^:\w+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = (s: string) => s === "*";
function computeScore(path: string, index: boolean | undefined): number {
let segments = path.split("/");
let initialScore = segments.length;
if (segments.some(isSplat)) {
initialScore += splatPenalty;
}
if (index) {
initialScore += indexRouteValue;
}
return segments
.filter((s) => !isSplat(s))
.reduce(
(score, segment) =>
score +
(paramRe.test(segment)
? dynamicSegmentValue
: segment === ""
? emptySegmentValue
: staticSegmentValue),
initialScore
);
}