site: fix locale switch

* 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,最后再拼回去做跳转。
This commit is contained in:
YuyingWu 2017-02-26 14:50:12 +08:00 committed by 偏右
parent 14d380f0f9
commit e8cf22ad0e

View File

@ -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)),
);