Skip to content

Commit 40808c2

Browse files
committed
Add URL normalization to remove trailing slashes in example detail URLs
- Add useEffect hook to normalize URLs by removing trailing slashes from /example-detail/ paths - This ensures consistent URL format without unnecessary trailing slashes - Automatically converts /example-detail/?id=... format to /example-detail?id=... format - Prevents automatic redirects to URLs with trailing slashes
1 parent 458c83d commit 40808c2

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

docs/src/pages/example-detail.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,23 @@ export default function ExampleDetail() {
134134
}
135135
}, [location.pathname, location.search, EXAMPLES_CONFIG.length]); // 监听 EXAMPLES_CONFIG 长度变化
136136

137+
// 监听URL变化并规范化URL格式,确保不带尾随斜杠
138+
useEffect(() => {
139+
// 检查当前URL是否包含尾随斜杠,并规范化为不带斜杠的格式
140+
if (location.pathname.includes('/example-detail/') && location.search.includes('id=')) {
141+
// 如果路径是 /example-detail/ 形式(带斜杠),将其规范化为 /example-detail 形式(不带斜杠)
142+
const normalizedPath = location.pathname.replace(/\/example-detail\/$/, '/example-detail');
143+
if (normalizedPath !== location.pathname) {
144+
// URL包含尾随斜杠,需要规范化,但不触发页面重新加载
145+
const normalizedUrl = `${normalizedPath}${location.search}`;
146+
// 仅在URL实际发生变化时进行替换
147+
if (normalizedUrl !== `${location.pathname}${location.search}`) {
148+
window.history.replaceState({}, document.title, normalizedUrl);
149+
}
150+
}
151+
}
152+
}, [location.pathname, location.search]);
153+
137154
// 监听路由变化,处理语言切换时的URL问题
138155
useEffect(() => {
139156
const handleLocationChange = () => {

0 commit comments

Comments
 (0)