繁体   English   中英

如何使用react-router-dom验证路径变量

[英]How to verify path variable with react-router-dom

我正在通过以下方式定义React项目的路由,使URL看起来像http://something.com/en-us/homehttp://something.com/fr-ca/home

<Route path="/:language/home" render={() => <Home/>}/>

在计划路径变量“:language”不是一种真实语言的情况下(即,将http://something.com/xyz/home重定向到http://something.com/en-us/home ),我最初调用componentDidMount setDefaultLanguage方法,该方法旨在使用浏览器的语言代码刷新页面。 而是,此方法在每次装入时刷新页面。

checkLangInMasterList(code) {
    let index = Object.keys(langMasterList).indexOf(code);
    // langMasterList is a JSON file with codes for 15
    // languages that the website will be offered in

    return index === -1 ? false : true;
}

setDefaultLanguage() {
    let browserLanguage = navigator.language || navigator.browserLanguage;
    let pathnames = window.location.pathname.split("/");
    // i.e. pathnames would look like
    // ["", "xyz", "home"]

    if (checkLangInMasterList(pathnames[1]) !== -1) {
        return;
    } else if (checkLangInMasterList(browserLanguage) === -1) {
        window.location = `/en-us/${pathnames[2]}`;
    } else if (
        checkLangInMasterList(pathnames[1]) === -1 &&
        checkLangInMasterList(browserLanguage) !== -1
    ) {
        window.location = `/${browserLanguage}/${pathnames[2]}`;
    }
}

如果浏览器的语言代码不存在(根本不存在或在允许的语言列表中),我如何正确处理对用户浏览器语言(如果在我们的列表中支持)或en-us的重定向?

您的checkLangInMasterList返回一个布尔值,而不是-1。 您的代码应如下所示:

if (!checkLangInMasterList(pathnames[1])) {
    // do stuff here
}

另外,如果path变量等于浏览器语言,则应停止重定向。

因此,根据您想要的逻辑,这里是它的样子:

if (checkLangInMasterList(pathnames[1]) {
    return
}
if (checkLangInMasterList(browserLanguage) {
    window.location = `/${browserLanguage}/${pathnames[2]}`
} else {
    window.location = `/${en-us}/${pathnames[2]}`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM