From e8cf22ad0ea1358df37d18c5f9e02fbc84ede55f Mon Sep 17 00:00:00 2001 From: YuyingWu Date: Sun, 26 Feb 2017 14:50:12 +0800 Subject: [PATCH] site: fix locale switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * antD首页从英文切换到中文时,replace导致链接错误 首页从英文转到中文,点击header上的“中文”时,链接会跳到 https://ant.design/index-cn/ant.design/ (Chrome)或者 https://index-cn/ant.design/ (Safari) bug来自handleLangChange函数下,最后对location.href.replace操作时出错,原因来自replace匹配到location.href的第一个/ ('https://ant.design/').replace('/', '/index-cn') 的运行结果是 https:/index-cn/ant.design/ 为了避免replace匹配到location.href的第一个/,我建议的方案是使用 location.origin + location.pathname.replace 最后,感谢antD团队开发出那么棒的UI~ * 英转中,url替换(带hash、query) 英转中URL问题,上一版使用了location.origin + location.pathname,会丢失query和hash。此版本原理还是用location.href做replace,鉴于首页pathname可能是/会在替换中匹配到https:后的第一个/,所以先把href的protocol部分提取出来,再做replace,最后再拼回去做跳转。 --- site/theme/template/Layout/Header.jsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/site/theme/template/Layout/Header.jsx b/site/theme/template/Layout/Header.jsx index 0c26486b8b..c52451399e 100644 --- a/site/theme/template/Layout/Header.jsx +++ b/site/theme/template/Layout/Header.jsx @@ -84,10 +84,14 @@ export default class Header extends React.Component { handleLangChange = () => { const pathname = this.props.location.pathname; + const currentProtocol = location.protocol + '//'; + const currentHref = location.href.substr(currentProtocol.length); + if (utils.isLocalStorageNameSupported()) { localStorage.setItem('locale', utils.isZhCN(pathname) ? 'en-US' : 'zh-CN'); } - location.href = location.origin + location.pathname.replace( + + location.href = currentProtocol + currentHref.replace( location.pathname, utils.getLocalizedPathname(pathname, !utils.isZhCN(pathname)), );