Skip to content

Commit 6724c8d

Browse files
committed
Fix example switching by delaying URL normalization to prevent interference
- Add timeout to URL normalization logic to prevent it from interfering with example switching - Ensure state updates complete before URL normalization runs - Add cleanup function to clear timeout
1 parent 27bf8a8 commit 6724c8d

1 file changed

Lines changed: 15 additions & 10 deletions

File tree

docs/src/pages/example-detail.tsx

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -137,18 +137,23 @@ export default function ExampleDetail() {
137137
// 监听URL变化并规范化URL格式,确保不带尾随斜杠
138138
useEffect(() => {
139139
// 检查当前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);
140+
// 使用setTimeout确保在所有状态更新完成后再执行规范化
141+
const timer = setTimeout(() => {
142+
if (location.pathname.includes('/example-detail/') && location.search.includes('id=')) {
143+
// 如果路径是 /example-detail/ 形式(带斜杠),将其规范化为 /example-detail 形式(不带斜杠)
144+
const normalizedPath = location.pathname.replace(/\/example-detail\/$/, '/example-detail');
145+
if (normalizedPath !== location.pathname) {
146+
// URL包含尾随斜杠,需要规范化,但不触发页面重新加载
147+
const normalizedUrl = `${normalizedPath}${location.search}`;
148+
// 仅在URL实际发生变化时进行替换
149+
if (normalizedUrl !== `${location.pathname}${location.search}`) {
150+
window.history.replaceState({}, document.title, normalizedUrl);
151+
}
149152
}
150153
}
151-
}
154+
}, 100); // 延迟执行,确保状态更新完成
155+
156+
return () => clearTimeout(timer);
152157
}, [location.pathname, location.search]);
153158

154159
// 监听路由变化,处理语言切换时的URL问题

0 commit comments

Comments
 (0)