Skip to content

Commit 661fe8b

Browse files
committed
Fix URL path issue when switching languages in example detail page
- Update URL handling to properly maintain language prefix when updating example parameters - Add route change listener to handle language switching correctly - Ensure example selection maintains correct URL structure with language prefixes The fix ensures that when users switch languages on the example detail page, the URL parameters are handled correctly and no extra slashes are added before the ?id parameter.
1 parent 09cb9d8 commit 661fe8b

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

docs/src/pages/example-detail.tsx

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,33 @@ export default function ExampleDetail() {
111111
}
112112
}, [location.search, EXAMPLES_CONFIG.length]); // 监听 EXAMPLES_CONFIG 长度变化
113113

114+
// 监听路由变化,处理语言切换时的URL问题
115+
useEffect(() => {
116+
const handleLocationChange = () => {
117+
const urlParams = new URLSearchParams(location.search);
118+
const urlExampleId = urlParams.get("id") || "hello-world";
119+
120+
// 确保示例存在
121+
const targetExample = EXAMPLES_CONFIG.find(ex => ex.id === urlExampleId) || EXAMPLES_CONFIG[0];
122+
123+
// 如果当前示例ID与URL参数不匹配,更新示例
124+
if (targetExample.id !== exampleId) {
125+
setExampleId(targetExample.id);
126+
setCode(targetExample.code);
127+
128+
// 运行新示例
129+
setTimeout(() => {
130+
if (previewRef.current) {
131+
runCodeWithContent(targetExample.code);
132+
}
133+
}, 0);
134+
}
135+
};
136+
137+
// 监听location变化,包括语言切换
138+
handleLocationChange();
139+
}, [location.pathname, location.search, EXAMPLES_CONFIG, exampleId]);
140+
114141
// 监听主题变化
115142
useEffect(() => {
116143
const handleThemeChange = () => {
@@ -193,8 +220,14 @@ export default function ExampleDetail() {
193220
setExampleId(selectedExample.id);
194221
setCode(selectedExample.code);
195222

196-
// 更新URL参数
197-
const newUrl = new URL(window.location.href);
223+
// 更新URL参数,保持当前语言路径前缀
224+
const currentPath = window.location.pathname;
225+
const currentLangPrefix = currentPath.startsWith('/zh/') ? '/zh' :
226+
currentPath.startsWith('/en/') ? '/en' : '';
227+
228+
// 构建正确的URL,处理语言前缀
229+
let newUrlPath = currentLangPrefix ? `${currentLangPrefix}/example-detail` : '/example-detail';
230+
const newUrl = new URL(window.location.origin + newUrlPath);
198231
newUrl.searchParams.set('id', selectedExample.id);
199232
window.history.replaceState({}, '', newUrl.toString());
200233

0 commit comments

Comments
 (0)