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

How to verify path variable with react-router-dom

我正在以 URL 看起来像 http://something.com/en-us/home or http://something.com/fr-ca/home 的方式为 React 项目定义路由:

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

在计划路径变量“:language”不是真正的语言(即重定向 http://something.com/xyz/home to 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 return 布尔值不是 -1。 您的代码应如下所示:

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

此外,如果路径变量等于浏览器语言,您应该停止重定向。

所以根据你想要的逻辑,它看起来像这样:

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